locked
downloading all files in directory ftp and c#

    Question

  • Hello,

    I am trying to download not one, but all files within a remote directory using FTP and C# and then save them to a local folder on my hard drive. How can I do this?
    john.strez
    Wednesday, May 27, 2009 1:54 AM

Answers

  • Hi John,

    For being able to download all files from a FTP directory to a local folder, you will have to list all files in the remote directory and then download them one by one. You can use the following code to do the same:

            string[] files = GetFileList();
            foreach (string file in files)
            {
                Download(file);
            }
    
            public string[] GetFileList()
            {
                string[] downloadFiles;
                StringBuilder result = new StringBuilder();
                WebResponse response = null;
                StreamReader reader = null;
                try
                {
                    FtpWebRequest reqFTP;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                    reqFTP.Proxy = null;
                    reqFTP.KeepAlive = false;
                    reqFTP.UsePassive = false;
                    response = reqFTP.GetResponse();
                    reader = new StreamReader(response.GetResponseStream());
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("\n");
                        line = reader.ReadLine();
                    }
                    // to remove the trailing '\n'
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    return result.ToString().Split('\n');
                }
                catch (Exception ex)
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }                
                    downloadFiles = null;
                    return downloadFiles;
                }
            }
    
            private void Download(string file)
            {                       
                try
                {                
                    string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;
                    Uri serverUri = new Uri(uri);
                    if (serverUri.Scheme != Uri.UriSchemeFtp)
                    {
                        return;
                    }       
                    FtpWebRequest reqFTP;                
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDir + "/" + file));                                
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);                
                    reqFTP.KeepAlive = false;                
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
                    reqFTP.UseBinary = true;
                    reqFTP.Proxy = null;                 
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);                
                    int Length = 2048;
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = responseStream.Read(buffer, 0, Length);               
                    while (bytesRead > 0)
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                    }                
                    writeStream.Close();
                    response.Close(); 
                }
                catch (WebException wEx)
                {
                    MessageBox.Show(wEx.Message, "Download Error");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Download Error");
                }
            }


    I have written and tested this code using Visual Studio 2005. It worked without giving any errors and I was able to download all files from my remote FTP folder. However, if you still face any issues while using it, please feel free to reply so that I can look into it.


    Thanks,
    Sumit

    [Please do not forget to mark as answer for a correct reply.]

    • Proposed as answer by sumitlathwal Wednesday, May 27, 2009 6:22 AM
    • Marked as answer by Reymarx Gereda Thursday, June 4, 2009 1:50 PM
    Wednesday, May 27, 2009 6:15 AM

All replies

  • Hi John,

    For being able to download all files from a FTP directory to a local folder, you will have to list all files in the remote directory and then download them one by one. You can use the following code to do the same:

            string[] files = GetFileList();
            foreach (string file in files)
            {
                Download(file);
            }
    
            public string[] GetFileList()
            {
                string[] downloadFiles;
                StringBuilder result = new StringBuilder();
                WebResponse response = null;
                StreamReader reader = null;
                try
                {
                    FtpWebRequest reqFTP;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
                    reqFTP.UseBinary = true;
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                    reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                    reqFTP.Proxy = null;
                    reqFTP.KeepAlive = false;
                    reqFTP.UsePassive = false;
                    response = reqFTP.GetResponse();
                    reader = new StreamReader(response.GetResponseStream());
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("\n");
                        line = reader.ReadLine();
                    }
                    // to remove the trailing '\n'
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    return result.ToString().Split('\n');
                }
                catch (Exception ex)
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    if (response != null)
                    {
                        response.Close();
                    }                
                    downloadFiles = null;
                    return downloadFiles;
                }
            }
    
            private void Download(string file)
            {                       
                try
                {                
                    string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;
                    Uri serverUri = new Uri(uri);
                    if (serverUri.Scheme != Uri.UriSchemeFtp)
                    {
                        return;
                    }       
                    FtpWebRequest reqFTP;                
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDir + "/" + file));                                
                    reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);                
                    reqFTP.KeepAlive = false;                
                    reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
                    reqFTP.UseBinary = true;
                    reqFTP.Proxy = null;                 
                    reqFTP.UsePassive = false;
                    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);                
                    int Length = 2048;
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = responseStream.Read(buffer, 0, Length);               
                    while (bytesRead > 0)
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                    }                
                    writeStream.Close();
                    response.Close(); 
                }
                catch (WebException wEx)
                {
                    MessageBox.Show(wEx.Message, "Download Error");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Download Error");
                }
            }


    I have written and tested this code using Visual Studio 2005. It worked without giving any errors and I was able to download all files from my remote FTP folder. However, if you still face any issues while using it, please feel free to reply so that I can look into it.


    Thanks,
    Sumit

    [Please do not forget to mark as answer for a correct reply.]

    • Proposed as answer by sumitlathwal Wednesday, May 27, 2009 6:22 AM
    • Marked as answer by Reymarx Gereda Thursday, June 4, 2009 1:50 PM
    Wednesday, May 27, 2009 6:15 AM
  • hi sumit

    im naren.i need, in single click i download folder from ftp using c#.net in 2008.
    Naren
    Monday, December 7, 2009 6:54 AM
  • Hi, guys if there is any network probs during download. My download will start where i left. 
    Any code for that....................
    Friday, January 22, 2010 7:29 AM
  • if ur going to use visual studio why not just use ftp task? it supports wildcards and multi-file downloads? *.* or 20??FA*.txt etc... soooo much easier than c#
    Tuesday, March 16, 2010 4:13 AM
  • hi sumit

    im naren.i need, in single click i download folder from ftp using c#.net in 2008.
    Naren
    You need to implement an event handler for your button. Or take a look at this web blog
    Sunday, June 27, 2010 10:32 PM
  • Hi sumit,

     

    I need to download multiple files from an ftp server,  am using ur code .

    but it is not saving the files list.

     

    What exactly I want to do is I need to download multiple files to folder and use the file one by one.

    For example

    IF I get the list of the files using ftpwebrequet.listdirectory

    to c:\Test\text.txt

    test.txt  contains, 

    A.txt

    B.txt

     

    I want to use use A.txt from text.txt for downloading from ftp server

    and B.txt again

     

    So i need to automate the process.

     

    Please help me.. very urgent.

     

    Thank u 

     

    Tuesday, August 3, 2010 11:53 PM
  • Hi Summit,

    Can I achieve this goal using PHP instead of C#? 

    Many thanks.

     

    Kindly,

    Ariel

    Thursday, August 12, 2010 4:38 PM
  • Hi,

    I have been using .NET/.NET CF FTP Component (link to componentforge removed) for my File Transfer needs. I hope this helps.
    The FTP component from ComponentForge mentioned by John Borders is illegaly based on code stolen from Rebex FTP component . ComponentForge (aka Safabyte) is in fact fraudulent Vietnamese company who stole most of their components from Rebex and other vendors. You may find more info about the case at http://cheated.by.safabyte.net and http://blog.safabyte.net .

    You don't have to trust us. Check the evidence yourself.

    You can reach us at support@rebex.net if you have further questions.

    Anyway. Following code shows how to download all files from remote directory using the genuine Rebex FTP (which workson both .NET and .NET CF):


    // create client, connect and log in 
    Ftp client = new Ftp();
    client.Connect("ftp.example.org");
    client.Login("username", "password");
    
    // download the content of '/wwwroot' directory and all subdirectories 
    // at the server to the 'c:\data' directory 
    client.GetFiles("/wwwroot/*", @"c:\data", FtpBatchTransferOptions.Recursive);
    
    client.Disconnect();
    
    
    
    


    Could you give more detailed description? Thanks very much! I'm new here, I do not fully understand the sample.
    Wednesday, August 18, 2010 11:47 PM
  • Hi Summit,

    Can I achieve this goal using PHP instead of C#

    Many thanks.

     

    Kindly,

    Ariel

    This thread is about .NET ftp library. You may want to search for PHP lib at this search result page.

    Cheers

    Felix

    Tuesday, September 28, 2010 6:43 AM
  • Hi John,

    For being able to download all files from a FTP directory to a local folder, you will have to list all files in the remote server directory and then download them one by one. You can use the following code to do the same:

     string
    
    
    
    
    
    
    
    
    [] files = GetFileList();
     foreach
    
    
    
    
    
    
    
    
     (string
    
    
    
    
    
    
    
    
     file in
    
    
    
    
    
    
    
    
     files)
     {
      Download(file);
     }
    
     public
    
    
    
    
    
    
    
    
     string
    
    
    
    
    
    
    
    
    [] GetFileList()
     {
      string
    
    
    
    
    
    
    
    
    [] downloadFiles;
      StringBuilder result = new
    
    
    
    
    
    
    
    
     StringBuilder();
      WebResponse response = null
    
    
    
    
    
    
    
    
    ;
      StreamReader reader = null
    
    
    
    
    
    
    
    
    ;
      try
    
    
    
    
    
    
    
    
    
      {
      FtpWebRequest reqFTP;
      reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
    
    
    
    
    
    
    
    
     Uri("ftp://"
    
    
    
    
    
    
    
    
     + ftpServerIP + "/"
    
    
    
    
    
    
    
    
    ));
      reqFTP.UseBinary = true
    
    
    
    
    
    
    
    
    ;
      reqFTP.Credentials = new
    
    
    
    
    
    
    
    
     NetworkCredential(ftpUserID, ftpPassword);
      reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
      reqFTP.Proxy = null
    
    
    
    
    
    
    
    
    ;
      reqFTP.KeepAlive = false
    
    
    
    
    
    
    
    
    ;
      reqFTP.UsePassive = false
    
    
    
    
    
    
    
    
    ;
      response = reqFTP.GetResponse();
      reader = new
    
    
    
    
    
    
    
    
     StreamReader(response.GetResponseStream());
      string
    
    
    
    
    
    
    
    
     line = reader.ReadLine();
      while
    
    
    
    
    
    
    
    
     (line != null
    
    
    
    
    
    
    
    
    )
      {
       result.Append(line);
       result.Append("\n"
    
    
    
    
    
    
    
    
    );
       line = reader.ReadLine();
      }
      // to remove the trailing '\n'
    
    
    
    
    
    
    
    
    
      result.Remove(result.ToString().LastIndexOf('\n'
    
    
    
    
    
    
    
    
    ), 1);
      return
    
    
    
    
    
    
    
    
     result.ToString().Split('\n'
    
    
    
    
    
    
    
    
    );
      }
      catch
    
    
    
    
    
    
    
    
     (Exception ex)
      {
      if
    
    
    
    
    
    
    
    
     (reader != null
    
    
    
    
    
    
    
    
    )
      {
       reader.Close();
      }
      if
    
    
    
    
    
    
    
    
     (response != null
    
    
    
    
    
    
    
    
    )
      {
       response.Close();
      }  
      downloadFiles = null
    
    
    
    
    
    
    
    
    ;
      return
    
    
    
    
    
    
    
    
     downloadFiles;
      }
     }
    
     private
    
    
    
    
    
    
    
    
     void
    
    
    
    
    
    
    
    
     Download(string
    
    
    
    
    
    
    
    
     file)
     {   
      try
    
    
    
    
    
    
    
    
    
      {  
      string
    
    
    
    
    
    
    
    
     uri = "ftp://"
    
    
    
    
    
    
    
    
     + ftpServerIP + "/"
    
    
    
    
    
    
    
    
     + remoteDir + "/"
    
    
    
    
    
    
    
    
     + file;
      Uri serverUri = new
    
    
    
    
    
    
    
    
     Uri(uri);
      if
    
    
    
    
    
    
    
    
     (serverUri.Scheme != Uri.UriSchemeFtp)
      {
       return
    
    
    
    
    
    
    
    
    ;
      } 
      FtpWebRequest reqFTP;  
      reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
    
    
    
    
    
    
    
    
     Uri("ftp://"
    
    
    
    
    
    
    
    
     + ftpServerIP + "/"
    
    
    
    
    
    
    
    
     + remoteDir + "/"
    
    
    
    
    
    
    
    
     + file));    
      reqFTP.Credentials = new
    
    
    
    
    
    
    
    
     NetworkCredential(ftpUserID, ftpPassword);  
      reqFTP.KeepAlive = false
    
    
    
    
    
    
    
    
    ;  
      reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;    
      reqFTP.UseBinary = true
    
    
    
    
    
    
    
    
    ;
      reqFTP.Proxy = null
    
    
    
    
    
    
    
    
    ;   
      reqFTP.UsePassive = false
    
    
    
    
    
    
    
    
    ;
      FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
      Stream responseStream = response.GetResponseStream();
      FileStream writeStream = new
    
    
    
    
    
    
    
    
     FileStream(localDestnDir + "\" + file, FileMode.Create);  
      int
    
    
    
    
    
    
    
    
     Length = 2048;
      Byte[] buffer = new
    
    
    
    
    
    
    
    
     Byte[Length];
      int
    
    
    
    
    
    
    
    
     bytesRead = responseStream.Read(buffer, 0, Length);  
      while
    
    
    
    
    
    
    
    
     (bytesRead > 0)
      {
       writeStream.Write(buffer, 0, bytesRead);
       bytesRead = responseStream.Read(buffer, 0, Length);
      }  
      writeStream.Close();
      response.Close(); 
      }
      catch
    
    
    
    
    
    
    
    
     (WebException wEx)
      {
      MessageBox.Show(wEx.Message, "Download Error"
    
    
    
    
    
    
    
    
    );
      }
      catch
    
    
    
    
    
    
    
    
     (Exception ex)
      {
      MessageBox.Show(ex.Message, "Download Error"
    
    
    
    
    
    
    
    
    );
      }
     }
    


    I have written and tested this code using Visual Studio 2005. It worked without giving any errors and I was able to download all files from my remote FTP folder. However, if you still face any issues while using it, please feel free to reply so that I can look into it.


    Thanks,
    Sumit

    [Please do not forget to mark as answer for a correct reply.]

    Good article. I still dont understand why VS do not support FTP natively
    Tuesday, September 28, 2010 3:26 PM
  • You may need this code that uses the Ultimate FTP component .

    C#

    // Create a new instance.
    Ftp client = new Ftp();
    // Connect to the FTP server.
    client.Connect( "myserver" );
    // Authenticate.
    client.Authenticate( "userName" , "password" );
    // ...
    // Download an entire directory '/myfolder' to 'c:\'.
    client.DownloadDirectory( "/myfolder" , "c:\\" );
    // ...
    // Disconnect.
    client.Disconnect();

    VB.NET

    ' Create a new instance.
    Dim client As New Ftp()
    ' Connect to the FTP server.
    client.Connect("myserver" )
    ' Authenticate.
    client.Authenticate("userName" , "password" )
    ' ...
    ' Download an entire directory '/myfolder' to 'c:\'.
    client.DownloadDirectory("/myfolder" , "c:\" )
    ' ...
    ' Disconnect.
    client.Disconnect()
    Monday, October 11, 2010 3:23 PM
  • i want to download files from the folder/subfolder/ in ftp c#
    ftp could online download files from the root folder i.e folder not from the child folder subfolder
    how can i do that
    can u plz send me some piece of code showing file download fron sub folder in ftp c#
    ill be highly thankful to you

    or mail me on winodjadhav@yahoo.com

     

    Thursday, October 14, 2010 2:54 PM
  • i want to download files from the folder/subfolder/ in ftp c#
    ftp could online download files from the root folder i.e folder not from the child folder subfolder
    how can i do that
    can u plz send me some piece of code showing file download fron sub folder in ftp c#
    ill be highly thankful to you

    please reply me on winodjadhav@yahoo.com


    vinod jadhav
    • Proposed as answer by EdwardInfant Wednesday, November 24, 2010 6:33 AM
    Thursday, October 14, 2010 3:03 PM
  • Hello,

     

    Considering that many developers in this forum ask how to download all files from FTP server folder, my team has created a code sample for this frequently asked programming task in Microsoft All-In-One Code Framework. You can download the code samples at:

     

    CSFTPDownload

     

    http://bit.ly/CSFTPDownload

     

    VBFTPDownload

     

    http://bit.ly/VBFTPDownload

    With these code samples, we hope to reduce developers’ efforts in solving the frequently asked

    programming tasks. If you have any feedback or suggestions for the code samples, please email us: onecode@microsoft.com.

    ------------

    The Microsoft All-In-One Code Framework (http://1code.codeplex.com) is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

    Our team listens to developers’ pains in MSDN forums, social media and various developer communities. We write code samples based on developers’ frequently asked programming tasks, and allow developers to download them with a short code sample publishing cycle. Additionally, our team offers a free code sample request service. This service is a proactive way for our developer community to obtain code samples for certain programming tasks directly from Microsoft.

    Thanks

    Microsoft All-In-One Code Framework

    • Proposed as answer by Mafaz Monday, September 26, 2011 1:05 PM
    Thursday, March 24, 2011 2:24 AM
  • I think that it is great that you have posted this code. I'm amazed at how complex it is. There is a lot for me to learn about C# coding...

    However, I ran the the demo app and, if I hit on ftp://ftp.microsoft.com it works perfectly. If I try to hit on the site I want to hit on, it fail saying the uri does not exist, even though it definitely does. What could be causing a bogus uri does not exist message? I would give out what is needed to log on but it is password protected site.

    I do know that if I log in with Filezilla, it shous the path as mylogin@ftp2.ftpsite.com/mail/ rather than what it probably is: ftp2.ftpsite.com/mylogin/mail/ In other words, it reroutes.

    At any rate, this looks like just what I need, except it doesn't serve me for the actual application i need it for.

    Any ideas?

    Thanks!


    -------------- Bill Ross

    PS: I can't debug this app. It says my debugger is installed incorrectly, even though I use it all the time for other apps. ?

    Wednesday, April 27, 2011 1:29 PM
  • Hi

    I am trying to connect to MAC OS machine.but i was unable to do it.i used the above code....

    please help me in this..

    Friday, May 27, 2011 10:47 AM
  • Its Really helpful. Thanks

    Varun Kumar
    Friday, June 24, 2011 12:19 PM
  • HI  simit

    Will you please say for download files  from sub directory  also..awaiting for your reply. 

    Friday, September 9, 2011 5:33 AM
  • Hello,

     

    Considering that many developers in this forum ask how to download all files from FTP server folder, my team has created a code sample for this frequently asked programming task in Microsoft All-In-One Code Framework. You can download the code samples at:

     

    CSFTPDownload

     

    http://bit.ly/CSFTPDownload

     

    VBFTPDownload

     

    http://bit.ly/VBFTPDownload

    With these code samples, we hope to reduce developers’ efforts in solving the frequently asked

    programming tasks. If you have any feedback or suggestions for the code samples, please email us: onecode@microsoft.com.

    ------------

    The Microsoft All-In-One Code Framework (http://1code.codeplex.com) is a free, centralized code sample library driven by developers' needs. Our goal is to provide typical code samples for all Microsoft development technologies, and reduce developers' efforts in solving typical programming tasks.

    Our team listens to developers’ pains in MSDN forums, social media and various developer communities. We write code samples based on developers’ frequently asked programming tasks, and allow developers to download them with a short code sample publishing cycle. Additionally, our team offers a free code sample request service. This service is a proactive way for our developer community to obtain code samples for certain programming tasks directly from Microsoft.

    Thanks

    Microsoft All-In-One Code Framework

    Thank you very much. I really needed a code to upload and download whole directories, and the examples helped me a lot.
    Monday, September 26, 2011 1:05 PM
  • Thank you Sir,

    your code really helped me.... :-)

    Saturday, October 8, 2011 10:33 AM
  • What about secure FTP?
    -------------- Bill Ross
    Saturday, October 8, 2011 11:36 AM
  • The code contains an assumption at line 175 of CSFTPDownload.FTPClientManager 
    where it thinks that the only valid return code from an ftp site that has just 
    received "NLST" (WebRequestMethods.Ftp.ListDirectory) is FtpStatusCode.DataAlreadyOpen.
    The assumption is wrong.  FileZilla on Windows (for example ) returns the code OpeningData (FtpStatusCode.DataAlreadyOpen).
    Tuesday, November 1, 2011 5:46 PM