C# file download from URL

It used to take some code to download a file from a URL over http connection. Today it’s fairly easy only couple of lines of code just using the .net libs. As you can see below.

using System.Net;
// Downloads a file from URL, saves locally
public static void getFileFromUrl( string psUrl, string psFileName )
{
    try
    {
        WebClient Client = new WebClient();
        Client.DownloadFile(psUrl, psFileName);
    }
    catch (Exception ex)
    {
        Console.WriteLine( “Err=” + ex );
    }
}

One Comment

  1. Use Credentials for better operation download….

    using System.Net;
    // Downloads a file from URL, saves locally
    public static void getFileFromUrl( string psUrl, string psFileName )
    {
    try
    {
    WebClient client = new WebClient();
    client.Credentials = System.Net.CredentialCache.DefaultCredentials;
    string copyDestination = Path.GetTempPath() + “\\docService\\” + fileName;
    client.DownloadFile(copySource, copyDestination);
    }
    catch (Exception ex)
    {
    Console.WriteLine( “Err=” + ex );
    }
    }

Leave a Reply