0

I want to list all files from my ftp folder, I am using this code. But it gives me twice the name of files. What is wrong with it?

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);
            }
        }
Firdavs Kurbonov
  • 1,252
  • 4
  • 16
  • 42

1 Answers1

0
  • Use a debugger to see what is contain in "response"
  • Make sure that your function is called only once.
  • Also, are your sure that the "duplicates" are not files with the same name but different absolute paths ?

Few remarks on your code:

  • Prefer using directives when manipulating streams, instead of manually closing them : here your code might throw exceptions without releasing the resources.
  • Avoid swallowing exceptions (even if you display them)

    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
            }
    
quantdev
  • 23,517
  • 5
  • 55
  • 88