w3resource

C# Program: Download content from multiple URLs with exception handling

C# Sharp Exception Handling: Exercise-13 with Solution

Write a C# program that reads a list of URLs from the user and downloads the content of each URL. Handle the exception if any URL is inaccessible.

Sample Solution:

C# Sharp Code:

using System;
using System.Net;

class Program {
  static void Main() {
    // Prompt the user to input URLs, one URL per line, and press Enter to complete
    Console.WriteLine("Input the URLs (one URL per line, press Enter to complete):");

    try {
      while (true) {
        // Read the URL entered by the user
        string url = Console.ReadLine();

        // Check if the entered URL is null, empty, or contains only whitespace
        if (string.IsNullOrWhiteSpace(url)) {
          // Break out of the loop if the entered URL is empty or whitespace
          break;
        }

        // Call the method to download content from the specified URL
        DownloadContent(url);
      }
    } catch (WebException ex) {
      // Catch block for handling WebException when accessing URLs
      Console.WriteLine("Error accessing URL: " + ex.Message);
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to download content from a specified URL and display it
  static void DownloadContent(string url) {
    // Create a new instance of WebClient to download content
    WebClient webClient = new WebClient();

    // Download the content from the provided URL
    string content = webClient.DownloadString(url);

    // Display the content of the downloaded URL
    Console.WriteLine("Content of URL '" + url + "':");
    Console.WriteLine(content);
    Console.WriteLine();
  }
}

Sample Output:

Input the URLs (one URL per line, press Enter to complete):
https://jsonplaceholder.typicode.com/posts/1
Content of URL 'https://jsonplaceholder.typicode.com/posts/1':
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

https://jsonplaceholder.typicode.com/posts/3
Content of URL 'https://jsonplaceholder.typicode.com/posts/3':
{
  "userId": 1,
  "id": 3,
  "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
  "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
}
 
Input the URLs (one URL per line, press Enter to complete):
https://jsonplaceholder.typicode.com/posts/4
Content of URL 'https://jsonplaceholder.typicode.com/posts/4':
{
  "userId": 1,
  "id": 4,
  "title": "eum et est occaecati",
  "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
}

https://jsonplaceholder.typicode.com/posts/101
Error accessing URL: The remote server returned an error: (404) Not Found.

Explanation:

In the above exercise,

  • The "Main()" method prompts the user to input URLs, one URL per line. The program reads URLs until the user presses Enter without entering any URL.
  • Inside the Main method, the URLs are passed to the DownloadContent method for downloading and displaying the content.
  • The DownloadContent method uses the WebClient class to download the given URL content using the DownloadString method.
  • If any exception occurs during the download, such as a WebException indicating an inaccessible URL, it is caught in the catch block in the "Main()" method. An appropriate error message is displayed.
  • Any other exceptions are caught by the generic catch block in the Main method, and a general error message is displayed.
  • The downloaded content is displayed using Console.WriteLine.

Flowchart:

Flowchart: Download content from multiple URLs with exception handling.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Calculate factorial with overflow exception handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/exception-handling/csharp-exception-handling-exercise-13.php