将可观察集合写入 txt 文件的最佳方法是什么?我目前有以下内容
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();
}
我不确定为什么它不会写入文件。有任何想法吗?
你可以轻松地写:
File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(item => item.ToString()));
但是,这需要您的Account
要覆盖的类ToString
提供您想要写入文件的信息。
如果你没有覆盖ToString
,我建议制定一种方法来处理这个问题:
string AccountToLine(Account account)
{
// Convert account into a 1 line string, and return
}
有了这个,你就可以写:
File.WriteAllLines("SavedAccounts.txt", SavedActionList.Select(AccountToLine));
编辑回应评论:
这根本行不通。我真的很困惑为什么,这就是我发布这个问题的原因。我通过在 file.Close() 之前插入一个 file.WriteLine("Hello") 来测试它,当我运行程序并检查文件时,它将包含的所有内容都是“Hello”
这实际上听起来就像您正在写出您的收藏而不向其中添加项目。如果集合为空,上面的代码(和你的代码)将创建一个空的输出文件,因为没有Account
要写出的实例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)