Home > DeveloperSection > Forums > Why this code is repeating files in listbox?
Tanuj Kumar

Total Post:134

Points:940
Posted on    August-18-2014 3:15 AM

 C# C# 
Ratings:


 1 Reply(s)
 681  View(s)
Rate this:

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);

            }

        }



Pravesh Singh

Total Post:411

Points:2881
Posted on    August-18-2014 3:36 AM

Hi Tanuj, 

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

        }


Don't want to miss updates? Please click the below button!

Follow MindStick