none
Listing all files from ftp server using C# RRS feed

  • Question

  • Hi All,

    I want to list all the files from ftp server using c#.........After googled i've got a code that list files from ftp server but just from the top directory or you can say that initial directory but i want to recursively get all the files and the subfolders that are inside the initial directory.How can we do that???????????Can  anyone help me??????????Here is the code which i am using for listing files from a single(initial) directory.

    private void getFileList(string FTPAddress, string username, string password)
            {
                List<string> files = new List<string>();
    
                try
                {
                    
                    //Create FTP request
                    FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress);
    
                    request.Method = WebRequestMethods.Ftp.ListDirectory;
                    request.Credentials = new NetworkCredential("anonymous", "anonymous");
                    request.UsePassive = true;
                    request.UseBinary = true;
                    request.KeepAlive = false;
    
                  
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(responseStream);
    
                    while (!reader.EndOfStream)
                    {
                        Application.DoEvents();
                        files.Add(reader.ReadLine());
                    }
    
                    //Clean-up
                    reader.Close();
                    responseStream.Close(); //redundant
                    response.Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("There was an error connecting to the FTP Server");
                }
    
             
    
                //If the list was successfully received, display it to the user
                //through a dialog
                if (files.Count != 0)
                {
                    foreach (string file in files)
                    {
                        listboxFiles.Items.Add(file);
                    }
    
                }
            }
    
    
    
    


     

    Saturday, January 14, 2012 1:31 PM

Answers

  • Hi Aamer Saeed,
    I wrote a working example for you. What this does is recursively lists any remote directory and fills a DirectoryItem structure with the proper contents (other files and directories). You may modify it to your liking. The code itself is simple, just requires parsing the response sent by the FTP server. Depending on what type of FTP server software it is, (UNIX, Windows, Windows NT, other), the response format may be different. What this means is that the code to parse the reponse will be different than mine (probably).

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Diagnostics;
    
    namespace ConsoleApplication6 {
    
        struct DirectoryItem {
            public Uri BaseUri;
    
            public string AbsolutePath {
                get {
                    return string.Format("{0}/{1}", BaseUri, Name);
                }
            }
    
            public DateTime DateCreated;
            public bool IsDirectory;
            public string Name;
            public List<DirectoryItem> Items;
        }
    
        class Program {
            static void Main(string[] args) {
                List<DirectoryItem> listing = GetDirectoryInformation("ftp://ftp.mywebsite.com/directory", "username", "password");
                Console.ReadKey();
            }
    
    
            static List<DirectoryItem> GetDirectoryInformation(string address, string username, string password) {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address);
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
    
                List<DirectoryItem> returnValue = new List<DirectoryItem>();
                string[] list = null;
    
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                    list = reader.ReadToEnd().Split(new string[] { "\r\n"},StringSplitOptions.RemoveEmptyEntries);
                }
    
                foreach (string line in list) {
                    // Windows FTP Server Response Format
                    // DateCreated    IsDirectory    Name
                    string data = line;
    
                    // Parse date
                    string date = data.Substring(0, 17);
                    DateTime dateTime = DateTime.Parse(date);
                    data = data.Remove(0, 24);
                    
                    // Parse <DIR>
                    string dir = data.Substring(0, 5);
                    bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase);
                    data = data.Remove(0, 5);
                    data = data.Remove(0, 10);
    
                    // Parse name
                    string name = data;
    
                    // Create directory info
                    DirectoryItem item = new DirectoryItem();
                    item.BaseUri = new Uri(address);
                    item.DateCreated = dateTime;
                    item.IsDirectory = isDirectory;
                    item.Name = name;
    
                    Debug.WriteLine(item.AbsolutePath);
                    item.Items = item.IsDirectory ? GetDirectoryInformation(item.AbsolutePath, username, password) : null;
    
                    returnValue.Add(item);
                }
    
                return returnValue;
            }
        }
    }
    
    

    Monday, January 16, 2012 2:39 AM
  • To make your code list recursively the files in the FTP server, you need to be able to distinguish between files and folders so that you can drill down the subfolders.

    The problem is that the output of the NLST and LIST commands (WebRequestMethods.Ftp.ListDirectory and WebRequestMethods.Ftp.ListDirectoryDetails) can vary depending on the FTP server and parsing all the alternatives can be rather tedious. I advise that you go and look for some FTP library and look at how they are doing it. There is a good candidate on codeplex, for instance, but you may find others in the wild.

    HTH
    --mc

    Monday, January 16, 2012 12:06 AM

All replies

  • To make your code list recursively the files in the FTP server, you need to be able to distinguish between files and folders so that you can drill down the subfolders.

    The problem is that the output of the NLST and LIST commands (WebRequestMethods.Ftp.ListDirectory and WebRequestMethods.Ftp.ListDirectoryDetails) can vary depending on the FTP server and parsing all the alternatives can be rather tedious. I advise that you go and look for some FTP library and look at how they are doing it. There is a good candidate on codeplex, for instance, but you may find others in the wild.

    HTH
    --mc

    Monday, January 16, 2012 12:06 AM
  • Hi Aamer Saeed,
    I wrote a working example for you. What this does is recursively lists any remote directory and fills a DirectoryItem structure with the proper contents (other files and directories). You may modify it to your liking. The code itself is simple, just requires parsing the response sent by the FTP server. Depending on what type of FTP server software it is, (UNIX, Windows, Windows NT, other), the response format may be different. What this means is that the code to parse the reponse will be different than mine (probably).

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.IO;
    using System.Diagnostics;
    
    namespace ConsoleApplication6 {
    
        struct DirectoryItem {
            public Uri BaseUri;
    
            public string AbsolutePath {
                get {
                    return string.Format("{0}/{1}", BaseUri, Name);
                }
            }
    
            public DateTime DateCreated;
            public bool IsDirectory;
            public string Name;
            public List<DirectoryItem> Items;
        }
    
        class Program {
            static void Main(string[] args) {
                List<DirectoryItem> listing = GetDirectoryInformation("ftp://ftp.mywebsite.com/directory", "username", "password");
                Console.ReadKey();
            }
    
    
            static List<DirectoryItem> GetDirectoryInformation(string address, string username, string password) {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address);
                request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
    
                List<DirectoryItem> returnValue = new List<DirectoryItem>();
                string[] list = null;
    
                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                    list = reader.ReadToEnd().Split(new string[] { "\r\n"},StringSplitOptions.RemoveEmptyEntries);
                }
    
                foreach (string line in list) {
                    // Windows FTP Server Response Format
                    // DateCreated    IsDirectory    Name
                    string data = line;
    
                    // Parse date
                    string date = data.Substring(0, 17);
                    DateTime dateTime = DateTime.Parse(date);
                    data = data.Remove(0, 24);
                    
                    // Parse <DIR>
                    string dir = data.Substring(0, 5);
                    bool isDirectory = dir.Equals("<dir>", StringComparison.InvariantCultureIgnoreCase);
                    data = data.Remove(0, 5);
                    data = data.Remove(0, 10);
    
                    // Parse name
                    string name = data;
    
                    // Create directory info
                    DirectoryItem item = new DirectoryItem();
                    item.BaseUri = new Uri(address);
                    item.DateCreated = dateTime;
                    item.IsDirectory = isDirectory;
                    item.Name = name;
    
                    Debug.WriteLine(item.AbsolutePath);
                    item.Items = item.IsDirectory ? GetDirectoryInformation(item.AbsolutePath, username, password) : null;
    
                    returnValue.Add(item);
                }
    
                return returnValue;
            }
        }
    }
    
    

    Monday, January 16, 2012 2:39 AM
  • Hi Dave,

     

    Thanks very much for your valuable answer it help me alot..................I've googled for this question and spent so much time but couldn't get the answer. And finally i post my question here and i've got the answer from you.

     

    Many Many Thanks,

    Aamer.

     

    Friday, January 27, 2012 1:40 PM
  • Thanks Dave and Mario for your help and support.

    Hi Aamer,

    Welcome to MSDN Forum.

    We are very glad to hear that you got the answer here.

    Thanks for your active participation in this community.

    If you have any difficulty in future programming, you are welcome to post here again.


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Sunday, January 29, 2012 5:33 AM
    Moderator
  • Hi Dave,

    Hope you are fine and working well............There is a bit of problem and i am not able to solve it even tried very hard that's why i am writing here........the below mentioned line throw an exception that "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0." some thing like that..............can you help me solving this............Actually this error is shown in my home pc where i am using window xp and visual 2010....................however in my university lab on window 7 it works fine by passing second parameter as System.Globalization.cultureinfo.createspecificculture("en-US").DateTimeFormat.

     DateTime dateTime = DateTime.Parse(date);

    DateTime dateTime = DateTime.Parse(date, System.Globalization.CultureInfo.CreateSpecificCulture("en-US").DateTimeFormat);

    Hope you understand my question.

    thanks,




    • Edited by Aamer Saeed Friday, February 17, 2012 7:46 PM
    Friday, February 17, 2012 7:41 PM
  • Thanks a lot for help :)
    Monday, March 25, 2013 7:35 PM
  • Great example! Thanks!
    Friday, June 6, 2014 9:12 PM
  • Thank to your example, it helps me a lot. :D God bless.
    Wednesday, August 8, 2018 3:54 AM