Question

Whats the best way to write an observable collection to a txt file? I currently have the following

public ObservableCollection<Account> SavedActionList = new ObservableCollection<Account>();   
using (System.IO.StreamWriter file = new System.IO.StreamWriter("SavedAccounts.txt")) 
        {
            foreach (Account item in SavedActionList)
            {
                file.WriteLine(item.ToString()); //doesn't work
            }
            file.Close();
        }

I'm not sure why it won't write to the file. Any ideas?

Was it helpful?

Solution

You can easily just write:

File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(item => item.ToString()));

However, this will require your Account class to override ToString to provide the information you wish to write to the file.

If you don't have an overridden ToString, I recommend making a method to handle this:

string AccountToLine(Account account)
{
   // Convert account into a 1 line string, and return
}

With this, you could then write:

File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(AccountToLine));

Edit in response to comments:

It simply doesn't work. I'm really confused as to why, which is why I posted the question. I tested it by inserting a file.WriteLine("Hello") before the file.Close() and when i run the program and check the file all it will have in it is "Hello"

This actually sounds like you're writing out your collection without adding items to it. If the collection is empty, the above code (and yours) will create an empty file of output, as there are no Account instances to write out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top