4

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); 
        }
    }
2
  • 7
    Why are you still using ArrayList? If you use List<string> your life will be much simpler. Commented Oct 21, 2013 at 5:47
  • And even if you do, don't name the object by it's type - ActorArrayList Commented Oct 21, 2013 at 5:50

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.