C# 将列表保存到txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15300572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:22:08  来源:igfitidea点击:

Saving lists to txt file

c#list

提问by Jared Price

I'm trying to save a list to a text file.

我正在尝试将列表保存到文本文件。

This is my code:

这是我的代码:

public void button13_Click(object sender, EventArgs e)
{
    TextWriter tw = new StreamWriter("SavedLists.txt");

    tw.WriteLine(Lists.verbList);
    tw.Close();
}

This is what I get in the text file:

这是我在文本文件中得到的:

System.Collections.Generic.List`1[System.String]

System.Collections.Generic.List`1[System.String]

Do I have to use ConvertAll<>? If so, I'm not sure how to use that.

我必须使用ConvertAll<>吗?如果是这样,我不确定如何使用它。

采纳答案by jgallant

Assuming your Generic List is of type String:

假设您的通用列表是字符串类型:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

或者,使用 using 关键字:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

回答by Reacher Gilt

@Jon's answer is great and will get you where you need to go. So why is your code printing out what it is. The answer: You're not writing out the contents of your list, but the String representation of your list itself, by an implicit call to Lists.verbList.ToString(). Object.ToString()defines the default behavior you're seeing here.

@Jon 的回答很棒,会带你去你想去的地方。那么为什么你的代码打印出它是什么。答案:您不是在写出列表的内容,而是通过隐式调用 Lists.verbList.ToString() 来写出列表本身的字符串表示。Object.ToString()定义了您在此处看到的默认行为。

回答by Eric Bole-Feysot

Framework 4: no need to use StreamWriter:

框架 4:无需使用 StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);