How to write an observable collection to a txt file?

廉价感情. 提交于 2019-12-23 04:37:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18834698/how-to-write-an-observable-collection-to-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!