Maattt
Maattt

Reputation: 177

How to write an ArrayList to a text file?

I have an ArrayList of strings and a text file called actors. I need to write all the elements in the ArrayList to a .txt file. Here is my code so far.

void WriteArrayList()
    {                        
        foreach (object actor in ActorArrayList)
        {
            File.WriteAllLines("C:\\actors.txt", actor); 
        }
    }

Upvotes: 4

Views: 16147

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

If you really must use ArrayList, and assuming you're using .NET 3.5 or higher, you can use the LINQ Cast method to convert it to a sequence of strings:

// .NET 4 and higher
File.WriteAllLines(@"c:\actors.txt", ActorArrayList.Cast<string>());

For .NET 3.5, you need to convert it to an array as well:

File.WriteAllLines(@"c:\actors.txt", ActorArrayList.Cast<string>().ToArray());

(The File.WriteAllLines overload taking IEnumerable<string> was only introduced in .NET 4.)

Note how you don't need to loop over the list yourself - the point of File.WriteAllLines is that it does it for you.

If you're not even using .NET 3.5, you should loop yourself - the foreach loop can implicitly cast for you:

using (TextWriter writer = File.CreateText(@"c:\actors.txt"))
{
    foreach (string actor in ActorArrayList)
    {
        writer.WriteLine(actor);
    }
}

If you can possibly use List<string> instead of ArrayList, you should. Generic collections were introduced in .NET 2, and since then there's been very little reason to use the non-generic collections.

Upvotes: 6

Related Questions