C# 我有一个控制台应用程序,可以读取和写入“人员”详细信息的获取/设置列表。它正常工作,直到我尝试将其写入文本文件。有人可以告诉我为什么将“Person”细节的最后一行写入我的文本文件而不是整个列表?
loadData();
Console.WriteLine("All People");
//1st query - just select all people
var queryAllPeople = from person in people select person;
foreach (Person p in queryAllPeople)
{
using (StreamWriter writer = new StreamWriter("people.txt"))
{
writer.WriteLine(p);
}
Console.WriteLine(p);
}
Console.ReadLine();
答案 0 :(得分:17)
将foreach放在using语句中。您在循环的每次迭代中都会覆盖该文件
答案 1 :(得分:6)
您正在为每次迭代编写一个具有相同名称的新文件。您需要在循环外创建StreamWriter
:
using (StreamWriter writer = new StreamWriter("people.txt"))
{
foreach (Person p in queryAllPeople)
{
writer.WriteLine(p);
Console.WriteLine(p);
}
}
答案 2 :(得分:3)
您每次都在重新创建文件。尝试:
using (StreamWriter writer = new StreamWriter("people.txt"))
{
foreach (Person p in queryAllPeople)
{
writer.WriteLine(p);
Console.WriteLine(p);
}
}
答案 3 :(得分:1)
使用接受附加作为参数的StreamWriter重载,以便附加 每次都是文件的值。
foreach (Person p in queryAllPeople)
{
using (StreamWriter writer = new StreamWriter("people.txt", true))
{
writer.WriteLine(p);
}
Console.WriteLine(p);
}
或者只是将foreach包装在using
语句中。