Maattt
Maattt

Reputation: 177

How to read a txt file and load the contents into an arraylist?

I am new to C# and to programming in general. I am trying to read the contents of a txt file and load them to an arraylist. I can't figure out what condition to use in my while loop.

void LoadArrayList()
{
    TextReader tr;
    tr = File.OpenText("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt");

    string Actor;
    while (ActorArrayList != null)
    {
        Actor = tr.ReadLine();
        if (Actor == null)
        {
            break;
        }
        ActorArrayList.Add(Actor);
    }  
}

Upvotes: 1

Views: 11361

Answers (5)

Kurubaran
Kurubaran

Reputation: 8902

You can do it with just 2 lines of code

string[] Actor = File.ReadAllLines("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt");
ArrayList list = new ArrayList(Actor);

Upvotes: 1

Dave Zych
Dave Zych

Reputation: 21897

If you look at the documentation for the TextReader.ReadLine method, you'll see that it returns either a string, or null if there are no more lines. So, what you can do is loop and check null against the results of the ReadLine method.

while(tr.ReadLine() != null)
{
    // We know there are more items to read
}

With the above, though, you're not capturing the result of ReadLine. So you need to declare a string to capture the result and to use inside the while loop:

string line;
while((line = tr.ReadLine()) != null)
{
    ActorArrayList.Add(line);
}

Also, I would suggest using a generic list, such as List<T> instead of the non-generic ArrayList. Using something like List<T> gives you more type safety and reduces the possibility of invalid assignments or casts.

Upvotes: 0

levininja
levininja

Reputation: 3258

Just rearrange it like this:

    Actor = tr.ReadLine();
    while (Actor != null)
    {
        ActorArrayList.Add(Actor);
        Actor = tr.ReadLine();
    }

Upvotes: 0

db9dreamer
db9dreamer

Reputation: 1715

 void LoadArrayList()
{
    TextReader tr;
    tr = File.OpenText("C:\\Users\\Maattt\\Documents\\Visual Studio 2010\\Projects\\actor\\actors.txt");

    string Actor;
    Actor = tr.ReadLine();
    while (Actor != null)
    {
        ActorArrayList.Add(Actor);
        Actor = tr.ReadLine();
    }

}

Upvotes: 2

Pankaj
Pankaj

Reputation: 2754

This is how it should be

 void LoadArrayList()
{
    string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Maattt\Documents\Visual Studio 2010\Projects\actor\actors.txt");

   // Display the file contents by using a foreach loop.
   foreach (string Actor in lines)
   {
       ActorArrayList.Add(Actor);
  }
}

Upvotes: 0

Related Questions