【问题标题】:Why this code is repeating files in listbox?为什么此代码在列表框中重复文件?
【发布时间】:2014-04-20 19:07:23
【问题描述】:

我想列出我的 ftp 文件夹中的所有文件,我正在使用此代码。但它给了我两倍的文件名。它有什么问题?

private void ListFilesOnServer()
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings.Get("IncomingFtpPath"));
                request.Credentials = new NetworkCredential("user", "password");
                request.Method = WebRequestMethods.Ftp.ListDirectory;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                while (!reader.EndOfStream)
                {
                    var line = reader.ReadLine();
                    if (System.IO.Path.GetExtension(line) == ".xml")
                    {
                        WaitingListBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(line));
                    }
                }

                reader.Close();
                response.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

【问题讨论】:

    标签: c# ftp webrequest ftp-client


    【解决方案1】:
    • 使用调试器查看“响应”中包含的内容
    • 确保您的函数只被调用一次。
    • 另外,您确定“重复”不是同名但绝对路径不同的文件吗?

    对您的代码的几点说明:

    • 在操作流时更喜欢使用指令,而不是手动关闭它们:您的代码可能会在不释放资源的情况下抛出异常。
    • 避免吞下异常(即使你显示它们)

      private void ListFilesOnServer()
      
      {
              try
              {
           FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConfigurationSettings.AppSettings.Get("IncomingFtpPath"));
      
                  request.Credentials = new NetworkCredential("user", "password");
      
                  request.Method = WebRequestMethods.Ftp.ListDirectory;
                  FtpWebResponse response = (FtpWebResponse)request.GetResponse();
      
                  using(StreamReader reader = new StreamReader(response.GetResponseStream())
                  {
                     string line = null;
                     while((line = reader.ReadLine()) != null)
                     {
                      if (System.IO.Path.GetExtension(line) == ".xml")
                      {
                        WaitingListBox.Items.Add(System.IO.Path.GetFileNameWithoutExtension(line));
                      }
                     }
                  }
              }
              catch (Exception e)
              {
                  MessageBox.Show(e.Message);
                  // throw e
              }
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-22
      • 2017-07-28
      • 2017-10-27
      • 2013-02-02
      • 2018-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多