Click here to Skip to main content
15,889,462 members
Please Sign up or sign in to vote.
3.40/5 (2 votes)
See more:
Hi Guys

I'm trying to read multiple files from a directory but the issue here is that, I get same output repeating multiple times.

The ListBox is just for display purposes

please see my code below
C#
protected void GetFileValues()
{
   var fileEntries = Directory.GetFiles(Server.MapPath("DataFiles"), "*.whl");
   List<string> list = new List<string>();
   
    foreach(string files in fileEntries)
    {
        
       
       string lineRead;
       StreamReader reader = new StreamReader(files);
                      while ((lineRead = reader.ReadLine()) != null) 
       {
          list.Add(lineRead);
       }//end while
         reader.Close();
                  
        ListBox1.Items.Add(list[5].ToString());
    }
}

current output--------------------Correct output
John------------------------------> John
John------------------------------> Aubrey
John------------------------------> Thomas
John------------------------------> Neil
Posted
v3
Comments
ZurdoDev 16-Apr-14 11:11am    
It seems like it should be pretty easy to see what is happening if you just put a breakpoint and step through the code.

1 solution

ListBox1.Items.Add(list[5].ToString());


You are calling this in a loop. Therefore you will get the same thing added to the listbox repeatedly.
 
Share this answer
 
Comments
Member 9528427 17-Apr-14 3:33am    
if I put the listbox outside the for loop, it only returns one the last item
Member 9528427 17-Apr-14 3:33am    
if I put the listbox outside the for loop, it only returns the last item
Rob Philpott 17-Apr-14 4:37am    
What is it that you are trying to do? At the moment you are effectively adding all the files together into a big list of string then for each file displaying the 5th item of that list.

Do you want to show the 5th item of each file, or is it something else?
Member 9528427 17-Apr-14 8:38am    
Hi Rob

that's exactly what i'm trying to archive (Show the 5th item of each file)
Rob Philpott 17-Apr-14 10:00am    
Ok, that's an easy fix, although I would say there are much better ways to do it.

Just move the List<string> list = new List<string> line after the foreach. At the moment that list is accumulating all files, but it sounds like you want to do it on a per-file basis.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900