为什么这段代码在列表框中重复文件?

时间:2014-04-20 19:07:23

标签: c# ftp webrequest ftp-client

我想列出我的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);
            }
        }

1 个答案:

答案 0 :(得分:0)

  • 使用调试器查看"响应"
  • 中包含的内容
  • 确保只调用一次函数。
  • 此外,您确定"重复"是不是具有相同名称但绝对路径不同的文件?

对您的代码的评论很少:

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

    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
            }