download a file in csharp

To download a file using C#, you can use the WebRequest class. Here's a sample code block that demonstrates the same:

main.cs
using System.Net;

// URL of the file to be downloaded
string fileUrl = "https://example.com/file.pdf"; 

// Destination path where the downloaded file will be stored
string destinationPath = @"C:\Downloads\file.pdf";

// Create a WebClient instance
using (WebClient webClient = new WebClient())
{
    try
    {
        // Download the file and save it to the destination path
        webClient.DownloadFile(fileUrl, destinationPath);
        Console.WriteLine("File Download Completed Successfully!");
    }
    catch (Exception ex)
    {
        Console.WriteLine("Error Occurred While Downloading File. Error Message: " + ex.Message);
    }
}
646 chars
23 lines

In the above code block, we first define the URL of the file to be downloaded and the location where it needs to be stored on the local system. We then create a WebClient instance and call the DownloadFile method, passing in the URL and destination path as parameters. If the download is successful, a success message is displayed, and if an exception is thrown, an error message is displayed.

gistlibby LogSnag