问题描述
将可观察的集合写入txt文件的最佳方法是什么?我目前有以下
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?
推荐答案
您可以轻松地编写:
File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(item => item.ToString()));
但是,这将需要您的Account
类重写ToString
,以提供您希望写入文件的信息.
However, this will require your Account
class to override ToString
to provide the information you wish to write to the file.
如果您没有覆盖的ToString
,我建议您采用一种方法来处理此问题:
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
}
这样,您就可以编写:
File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(AccountToLine));
根据评论进行
Edit in response to comments:
这听起来好像是您在不添加任何项目的情况下写出您的收藏.如果集合为空,则上面的代码(和您的代码)将创建一个空的输出文件,因为没有要写入的Account
实例.
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.
这篇关于如何将可观察的集合写入txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!