50

How to List Directory Contents with FTP in C# ?

I am using below code to List Directory Contents with FTP it is returning result in XML format ,but i want only the name of directory not the whole content.

How i Can do that ?

public class WebRequestGetExample
{
    public static void Main ()
    {
        // Get the object used to communicate with the server.
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

        // This example assumes the FTP site uses anonymous logon.
        request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        Console.WriteLine(reader.ReadToEnd());

        Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

        reader.Close();
        response.Close();
    }
}

MSDN

Sevle
  • 3,109
  • 2
  • 19
  • 31
Swapnil Gupta
  • 8,751
  • 15
  • 57
  • 75
  • I would use NameSearchCondition("*.*", SearchConditionFileTypes.Directory) as the search condition parameter ListDirectory method of the [ultimate ftp](http://www.componentpro.com/ftp.net/). See this example: http://www.componentpro.com/doc/ftp/ComponentPro.Net.Ftp.ListDirectory%28ComponentPro.IO.SearchCondition%29.htm – Peter Dec 23 '14 at 14:20

7 Answers7

69

Try this:

FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
ftpRequest.Credentials =new NetworkCredential("anonymous","janeDoe@contoso.com");
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());

List<string> directories = new List<string>();

string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
    directories.Add(line);
    line = streamReader.ReadLine();
}

streamReader.Close();

It gave me a list of directories... all listed in the directories string list... tell me if that is what you needed

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
mint
  • 3,341
  • 11
  • 38
  • 55
  • Hi, Your code is returning the result in XML format I only want remote system directories because i need to bind that directory names to a treeview. Getting XML will not work for me . – Swapnil Gupta Jul 21 '10 at 12:21
  • @swapnil Did my above code (i edited) work for you? just curious – mint Jul 21 '10 at 17:43
  • It returns me [DIR] Swapnil. . . . . . . . . . . . . Jul 21 09:43 where "Swapnil" is the name of the directory. I dont want all other things buddy just name of the directory i have to display in treeview . I cannot show all these details in treeview. Any suggestions or modifications ? – Swapnil Gupta Jul 22 '10 at 04:36
  • 5
    @Swapnil Gupta, it's not the code's fault that you get result in HTML, it's your FTP server's settings. – nightcoder Oct 03 '11 at 00:59
  • @mint hi mint i tried your code but i get an error of Object name: 'System.Net.Sockets.NetworkStream'. – Reynan Jul 05 '16 at 04:04
1

You are probably looking for PrintWorkingDirectory

leppie
  • 115,091
  • 17
  • 196
  • 297
  • When i am using PrintWorkingDirectory it is giving me error : "The requested FTP command is not supported when using HTTP proxy" FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri); ftpRequest.Credentials = new NetworkCredential("...", "..."); ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory; FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse(); //Error StreamReader streamReader = new StreamReader(response.GetResponseStream()); String sResult = streamReader.ReadToEnd(); streamReader.Close(); – Swapnil Gupta Jul 21 '10 at 12:20
  • Try changing ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory to ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkDirectory in your code... – mint Jul 21 '10 at 12:28
  • @monO : "The requested FTP command is not supported when using HTTP proxy" . This exception i am getting on line " FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();" – Swapnil Gupta Jul 21 '10 at 12:35
1

You need ListDirectory that lists the directory contents

EDIT: Or you can use this Chilkat library that wraps it up nicely for you

Iain Ward
  • 9,850
  • 5
  • 34
  • 41
  • ListDirectory is also listing the results in XML format . I only want remote system directories because i need to bind that directory names to a treeview. Getting XML will not work for me . Thanks. – Swapnil Gupta Jul 21 '10 at 12:22
  • Ya i gone through Chilkat library but i dont want to use any 3rd party. Thanks. Any other suggestion you have ? – Swapnil Gupta Jul 21 '10 at 12:24
  • I dont think it'll return anything but xml, but i could be wrong. You may have to just parse the xml into text unless you can specify the httpwebresponse to return plain text? – Iain Ward Jul 21 '10 at 12:48
1

Some proxies reformat the directory listing, so it's quite difficult to parse a directory listing reliably unless you can guarantee that the proxy doesn't change

Konektiv
  • 11
  • 1
0

There is a method GetDirectoryInformation() in following link which fetches files and directories recursively from a FTP directory.

Getting files from FTP directory recursively

Pabitra Dash
  • 1,461
  • 2
  • 21
  • 28
0

Simplest and most Efficient way to Get FTP Directory Contents:

var contents = GetFtpDirectoryContents(new Uri("ftpDirectoryUri"), new NetworkCredential("userName", "password"));

    public static List<string> GetFtpDirectoryContents(Uri requestUri, NetworkCredential networkCredential)
    {
        var directoryContents = new List<string>(); //Create empty list to fill it later.
        //Create ftpWebRequest object with given options to get the Directory Contents. 
        var ftpWebRequest = GetFtpWebRequest(requestUri, networkCredential, WebRequestMethods.Ftp.ListDirectory);
        try
        {
            using (var ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse()) //Excute the ftpWebRequest and Get It's Response.
            using (var streamReader = new StreamReader(ftpWebResponse.GetResponseStream())) //Get list of the Directory Contentss as Stream.
            {
                var line = string.Empty; //Initial default value for line.
                do
                {
                    line = streamReader.ReadLine(); //Read current line of Stream.
                    directoryContents.Add(line); //Add current line to Directory Contentss List.
                } while (!string.IsNullOrEmpty(line)); //Keep reading while the line has value.
            }
        }
        catch (Exception) { } //Do nothing incase of Exception occurred.
        return directoryContents; //Return all list of Directory Contentss: Files/Sub Directories.
    }

    public static FtpWebRequest GetFtpWebRequest(Uri requestUri, NetworkCredential networkCredential, string method = null)
    {
        var ftpWebRequest = (FtpWebRequest)WebRequest.Create(requestUri); //Create FtpWebRequest with given Request Uri.
        ftpWebRequest.Credentials = networkCredential; //Set the Credentials of current FtpWebRequest.

        if (!string.IsNullOrEmpty(method))
            ftpWebRequest.Method = method; //Set the Method of FtpWebRequest incase it has a value.
        return ftpWebRequest; //Return the configured FtpWebRequest.
    }
BenSabry
  • 483
  • 4
  • 10
-1

If you want to list the name of the files that are inside de directory, you have to put (reqFTP.Proxy = null;) before you invoke (reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;).

Hope this can help you!