Streamwriter(不能输入全文)c#

时间:2016-09-16 19:06:41

标签: streamwriter

问题是当我将数据打印到" M100.csv"文件,我只看到一行:

                    writer1.WriteLine("{0} {1} {2} {3} {4} {5} {6}",
                    houses[i].District, houses[i].Street, houses[i].Number,
                    houses[i].Type, houses[i].Years, houses[i].Area, houses[i].Rooms);
                    writer1.WriteLine("\n");

" writer1"必须打印两行不同的房子,但它只打印一个。我确定我的其他方法运行正常。 我也看不到这一行:

             writer.WriteLine("{0} {1}","Duomenys apie visus murinius namus, kuriu plotas yra daugiau nei 100kv.m. :\n",
             "Rajonas \t Gatve \t Numeris \t Tipas \t Metai \t Plotas \t Kambariu skaicius \n");
             writer.WriteLine("\n");

完整代码:

public static void Print(Houses[] houses,int amount, int[] BrickHouseNumber,int[] BlockHouseNumber)
    {

        using (StreamWriter writer = new StreamWriter("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.4\\M100.csv"))
         {
             writer.WriteLine("{0} {1}","Duomenys apie visus murinius namus, kuriu plotas yra daugiau nei 100kv.m. :\n",
             "Rajonas \t Gatve \t Numeris \t Tipas \t Metai \t Plotas \t Kambariu skaicius \n");
             writer.WriteLine("\n");
         }
        for (int i = 0; i < amount; i++)
        {
            if (BrickHouseNumber[i] > 0)
            {
                using (StreamWriter writer1 = new StreamWriter("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.4\\M100.csv"))
                {
                    writer1.WriteLine("{0} {1} {2} {3} {4} {5} {6}",
                    houses[i].District, houses[i].Street, houses[i].Number,
                    houses[i].Type, houses[i].Years, houses[i].Area, houses[i].Rooms);
                    writer1.WriteLine("\n");
                 }
            }

} }

1 个答案:

答案 0 :(得分:0)

使用仅路径构造函数声明StreamWriter将在该位置创建或覆盖该文件。由于您为每次写入创建了新的流编写器,因此您实际上是截断并重新启动文件,并最终以单行文本结束。在不重构代码的情况下,您可以通过将构造函数更改为附加而不是覆盖,通过将true传递给构造函数重载来修复此行为。

 new StreamWriter("C:\\Users\\Andrius\\Desktop\\Mokslams\\C#\\Pratybos\\P2\\P2.4\\M100.csv", true)

此外,WriteLine方法将自动添加行结尾。假设Windows环境,换行符,回车符和另一个换行符,使用WriteLine("\n")添加。这将导致大量的空白区域。