如何在C#中使用FTP列出目录内容?
我正在使用下面的代码通过FTP列出目录内容,它以XML格式返回结果,但是我只希望目录名称而不是整个内容。
我该怎么做?
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
尝试这个:
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();
它给了我一个目录列表…全部列在目录字符串列表中…告诉我这是否是您所需要的