2

C# 我有一个控制台应用程序,它读取和写入“人员”详细信息的获取/设置列表。在我尝试将其写入文本文件之前,它都可以正常工作。有人能告诉我为什么这会将“人员”详细信息的最后一行写入我的文本文件而不是整个列表吗?

        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();
4

4 回答 4

20

将 foreach 放在 using 语句中。您在循环的每次迭代中都覆盖了文件

于 2012-11-30T13:45:27.193 回答
7

您正在为每次迭代编写一个具有相同名称的新文件。您将需要创建StreamWriter循环外部:

using (StreamWriter writer = new StreamWriter("people.txt"))
{
    foreach (Person p in queryAllPeople)
    {
        writer.WriteLine(p);
        Console.WriteLine(p);
    }
}
于 2012-11-30T13:45:45.190 回答
4

您每次都在重新创建文件。尝试:

using (StreamWriter writer = new StreamWriter("people.txt"))
{
    foreach (Person p in queryAllPeople)
    {
        writer.WriteLine(p);
        Console.WriteLine(p);
    }

}
于 2012-11-30T13:46:25.880 回答
3

使用接受 append 作为参数的StreamWriter的重载,以便每次都将值附加到文件中。

foreach (Person p in queryAllPeople)
{
  using (StreamWriter writer = new StreamWriter("people.txt", true))
  {

     writer.WriteLine(p);

  }
  Console.WriteLine(p);
}

或者只是将 foreach 包装在using语句中。

于 2012-11-30T13:46:44.350 回答