s

C# download file from ftp to folder edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 08 September 2020 | 3722

In this article, we will write code to download file from an FTP server.

Sample Code

public static void DownloadFile(string userName, string password, string ftpSourceFilePath, string localDestinationFilePath)
{

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSourceFilePath);
    request.Method = WebRequestMethods.Ftp.DownloadFile;

    request.Credentials = new NetworkCredential(userName, password);
    request.UsePassive = true;

    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
        Stream responseStream = response.GetResponseStream();
        using (StreamReader reader = new StreamReader(responseStream))
        {
            char[] buffer = new char[100000000];
            int readlength = 0;
            int readIndex = 0;
            readlength = reader.Read(buffer, readIndex, 100000000);

            if (File.Exists(localDestinationFilePath))
            {
                File.Delete(localDestinationFilePath);
            }
            while (readlength > 0)
            {
                using (StreamWriter streamwriter = new StreamWriter(localDestinationFilePath, true))
                {
                    streamwriter.Write(buffer, readIndex, readlength);
                }
                readIndex = readIndex   readlength;
                readlength = reader.Read(buffer, readIndex, 2048);
            }
            reader.Close();
        }
        Console.WriteLine("Download Complete, status {0}", response.StatusDescription);
        response.Close();
    }
}
           
                    

You can call the above function by using the code below.

string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/");
DownloadFile("yourftpusername", "yourftppassword", "ftp://yourserver.com/path/filename.ext", path  @"filename.CSV");               
                    

the above code will download the file to ~/Files folder.

Check this article to download file from a url C# download file from url