How to download a file from a server using C# (.NET)

If you are trying to Download A File From A Server using C#, it is a relatively painless and easy technique. The following will show you how to download a known file from a website using C# .NET. If you needed the solution in VB.NET then the change is not too hard given how similar the two llanguage really are, case sensitivity and semi-colons being the main changes.

For our example, we'll download the robots.txt file from the server. It is not about downloading a website page because the page might just be a virtual page and be stored in a database. This example is talking about downloading a physical file from the server such as robots.txt which nearly all websites will have.

The first step is to reference a library using the Using keyword at the top of the program. You can reference the function direct but as that it is old hat, we'll use Using instead.

using System.Net;

Set up the credentials that we are going to connect with...

NetworkCredential credentials = new NetworkCredential(sUser, sPassword);

Next create a request for the file you wish to download.

FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
downloadRequest.Credentials = credentials;

The value of fileUrl should be "ftp://" + Host + RemoveFilename

try
{
    string fileUrl = "ftp://(Your server/Folder Location)/robots.txt";
    string localFilePath = "C:\\tempobots.txt";

    if (File.Exists(localFilePath))
        File.Delete(localFilePath);

    FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
    downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    downloadRequest.Credentials = credentials;

    using (FtpWebResponse downloadResponse =(FtpWebResponse)downloadRequest.GetResponse())
    using (Stream sourceStream = downloadResponse.GetResponseStream())
    using (Stream targetStream = File.Create(localFilePath))
    {
        byte[] buffer = new byte[10240];
        int read;
        while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            targetStream.Write(buffer, 0, read);
        }
    }
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("Retrieved : ");
}
catch (Exception ex)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Failed : " + ex.Message);
}

If everything has gone to plan, the file robots.txt will now exist in the C:\temp folder of your local machine. If any errors occurs, you will need to investigate. It'll probably be linked to your credentials.

Tags - .NET   FTP

Last Modified : June 2023


About... / Contact.. / Cookie...