How to List Directory Contents with FTP in C#?

2020-01-25 00:39发布

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

7条回答
Lonely孤独者°
2楼-- · 2020-01-25 00:47

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!

查看更多
男人必须洒脱
3楼-- · 2020-01-25 00:47

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

Getting files from FTP directory recursively

查看更多
神经病院院长
4楼-- · 2020-01-25 00:52

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

查看更多
ゆ 、 Hurt°
5楼-- · 2020-01-25 01:06

You need ListDirectory that lists the directory contents

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

查看更多
爷的心禁止访问
6楼-- · 2020-01-25 01:10

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

查看更多
该账号已被封号
7楼-- · 2020-01-25 01:10

You are probably looking for PrintWorkingDirectory

查看更多
登录 后发表回答