在C#中从FTP服务器检索文件列表

时间:2009-11-13 17:08:49

标签: c# ftp

我正在尝试从FTP服务器检索文件列表,但我得到了一些奇怪的非ASCII响应。

以下是我正在使用的代码:

 public string[] getFileList(string mask)
 {
   if(!logined)
   {
     login();
   }
   Socket cSocket = createDataSocket();
   this.getSslDataStream(cSocket);
   sendCommand("PASV");
   sendCommand("LIST " + "*"+mask);
   stream2.AuthenticateAsClient(remoteHost,
      null,
      System.Security.Authentication.SslProtocols.Ssl3 |
      System.Security.Authentication.SslProtocols.Tls,
      true);
   if(!(retValue == 150 || retValue == 125))
   {
     throw new IOException(reply.Substring(4));
   }
   StringBuilder mes = new StringBuilder();       
   while(true)
   {
     int bytes = cSocket.Receive(buffer, buffer.Length, 0);
     mes.Append(ASCII.GetString(buffer, 0, bytes));
     if(bytes < buffer.Length)
     {
       break;
     }
   }
   string[] seperator = {"\r\n"};
   string[] mess = mes.ToString().Split(seperator, StringSplitOptions.RemoveEmptyEntries);
   cSocket.Close();
   readReply();
   if(retValue != 226)
   {
     throw new IOException(reply.Substring(4));
   }
   return mess;
 }

我从FTP服务器获得的响应如下:

WRITE:PASV

READ:227 Entering Passive Mode (10,0,2,24,5,119)`

WRITE:LIST *.dat

READ:150 Opening ASCII mode data connection for /bin/ls.

READ:226 Transfer complete.

它停在那里。它返回的字符串数组包含一个带有一些非ascii字符的索引。看起来像一堆垃圾。也许我的ASCII.GetString部分错了?我不太确定。

提前致谢。

2 个答案:

答案 0 :(得分:6)

我为所有FtpWebRequest东西写了一个非常好用的包装器库。如果你想看看它,那就在https://gist.github.com/1242616

我在很多生产环境中使用它并且它还没有让我失望。

答案 1 :(得分:4)

对于它的价值,System.Net命名空间具有以{.Net 2.0开头的FtpWebRequestFtpWebResponse类。

以下是我使用的一些代码,用于将服务器的文件写入本地文件:

...
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(address);
ftpRequest.Credentials = new NetworkCredential(username, password);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftpRequest.KeepAlive = false;

FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

sr = new StreamReader(ftpResponse.GetResponseStream());
sw = new StreamWriter(new FileStream(fileName, FileMode.Create));

sw.WriteLine(sr.ReadToEnd());
sw.Close();

ftpResponse.Close();
sr.Close();
...
相关问题