09/01/2015 by Nitesh

Download Image Files From FTP Server in C#

Friends,

In my previous posts, I dealt with How To List Files From FTP Server, How To Delete File From FTP Server. In this post, we will see how can we can download an image file from FTP server using C# from within your Console or Windows Forms Application.

        private StreamReader DownloadFileFromFTP()
        {
             var request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/test.jpg");
             request.Method = WebRequestMethods.Ftp.DownloadFile;
             request.Credentials = new NetworkCredential("username", "password");
             request.UseBinary = true;
             
             using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
             {
                   using (Stream responseStream = response.GetResponseStream())
                   {
                        using (FileStream fs = new FileStream(destFileName, FileMode.Create))
                        {
                              byte[] buffer = new byte[102400];
                              int read = 0;
                              do
                              {
                                   read = responseStream.Read(buffer, 0, buffer.Length);
                                   fs.Write(buffer, 0, read);
                                   fs.Flush();
                              } while (!(read == 0));

                              fs.Flush();
                              fs.Close();
                        }
                   }
             }
        }

The above code downloads a file named “test.jpg” from the root location of the server “www.server.com”. If you see the code,we created an object of FtpWebRequest class and this time, we passed the RequestMethod as DownloadFile. This command tells the CLR to download the mentioned file from the server. Also, since we are dealing with images, we tell the server to transfer data in Binary format.

Hope you like this post! Keep learning and sharing! Cheers!

#C##Ftp#How To?#Winforms