读取FTP服务器文件列表代码如下:
public string[] GetFileList(string mask)
{
  if ( !this.loggedin ) this.Login();
  Socket cSocket = createDataSocket();
  this.sendCommand("NLST " + mask);
  if(!(this.resultCode == 150 || this.resultCode == 125))
    throw new FtpException(this.result.Substring(4));  this.message = "";
  DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
  while( timeout > DateTime.Now )
  {
    int bytes = cSocket.Receive(buffer, buffer.Length, 0);  //此处出现异常。
    this.message += ASCII.GetString(buffer, 0, bytes);    if ( bytes < this.buffer.Length ) break;
  }  string[] msg = this.message.Replace("\r","").Split('\n');  cSocket.Close();  return msg;
}在cSocket.Receive()处出现异常。信息如下:
未处理的“System.Net.Sockets.SocketException”类型的异常出现在 system.dll 中。
其他信息: 远程主机强迫关闭了一个现有的连接。由于我是用TimerTick对FTP服务器的文件夹进行监测的,查看是否有文件到达。在文件夹为空情况下,首次的监测正常,即根据返回的信息能说明文件夹为空。但是第二次就出现了如上异常。
请高手解答,谢谢。

解决方案 »

  1.   

    catch一下就好了,抛出错误
    ftp文件夹为空,当然读取不到数据了
      

  2.   

    看看这样:#region 文件操作
      /// <summary>
      /// 获得文件列表
      /// </summary>
      /// <param name="strMask">文件名的匹配字符串</param>
      /// <returns></returns>
      public string[] Dir(string strMask)
      {
       // 建立链接
       if(!bConnected)
       {
        Connect();
       }   //建立进行数据连接的socket
       Socket socketData = CreateDataSocket();
       
       //传送命令
       SendCommand("NLST " + strMask);   //分析应答代码
       if(!(iReplyCode == 150 || iReplyCode == 125 || iReplyCode == 226))
       {
        throw new IOException(strReply.Substring(4));
       }   //获得结果
       strMsg = "";
       while(true)
       {
        int iBytes = socketData.Receive(buffer, buffer.Length, 0);
        strMsg += ASCII.GetString(buffer, 0, iBytes);
        if(iBytes < buffer.Length)
        {
         break;
        }
       }
       char[] seperator = {'\n'};
       string[] strsFileList = strMsg.Split(seperator);
       socketData.Close();//数据socket关闭时也会有返回码
       if(iReplyCode != 226)
       {
        ReadReply();
        if(iReplyCode != 226)
        {
         throw new IOException(strReply.Substring(4));
        }
       }
       return strsFileList;
      }
      

  3.   

    to 3只熊熊:你的代码跟我的大同小异。难道你的不会出现这样的异常?我想知道的是为什么会出现这种情况。文件夹为空,Socket也会返回空的信息,以此来提醒用户文件夹为空,而不是抛出异常啊。
      

  4.   

    不是在SendCommand("NLST ")时出现异常,而是返回正确的文件列表返回码后执行cSocket.Receive时出现异常.