如何将可观察的集合写入txt文件? [英] How to write an observable collection to a txt file?

查看:120
本文介绍了如何将可观察的集合写入txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将可观察的集合写入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:

它根本不起作用.我真的很困惑为什么,这就是为什么我发布了这个问题.我通过在file.Close()之前插入file.WriteLine("Hello")进行测试,并在运行程序并检查文件时将其全部保存为"Hello"

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"

这听起来好像是您在不添加任何项目的情况下写出您的收藏.如果集合为空,则上面的代码(和您的代码)将创建一个空的输出文件,因为没有要写入的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文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆