C#StreamWriter没有写入文件

时间:2012-03-19 14:36:30

标签: c# streamwriter

basicLog是名称和时间戳列表。我想把它们写到一个文件中。我得到的两个错误是';'在StreamWriter行和'file'上。在第二行。

';'错误是:可能错误的空语句 文件错误是:当前上下文中不存在名称“file”。

文件创建得很好,但没有任何内容写入。我对当前上下文中不存在的文件感到困惑,因为在创建之前的行上。谢谢你的帮助。

foreach (BasicLog basicLog in emailAttach)
{
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true));
    file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}

4 个答案:

答案 0 :(得分:5)

是的,你确实有一个错误的空声明。

删除';'并缩进以显示原因:

foreach (BasicLog basicLog in emailAttach)
{
   using (System.IO.StreamWriter file = 
            new System.IO.StreamWriter(@"C:\\sorted.txt", true))  //;
   {
      file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - "
             + basicLog.EventTime + "\n");
   }
}

WriteLine()语句(应该)在using()的控制之下。 {}使更清楚。

这会有效,但请注意,效率非常低,您要多次重新打开文件(for append)。

因此最好反转foreach / using:

using (System.IO.StreamWriter file = 
      new System.IO.StreamWriter(@"C:\\sorted.txt", true)) 
{
   foreach (BasicLog basicLog in emailAttach)
   {
        file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " 
            + basicLog.EventTime + "\n");
   }
}

答案 1 :(得分:4)

Ooops在使用行的末尾有一个分号???

也许你的意图是:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true))
{
    foreach (BasicLog basicLog in emailAttach) 
    {          
        file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n"); 
    } 
}

好奇,今天早上发生了同样的事情: - )

答案 2 :(得分:2)

您的file实例将在此行之后立即处理(因为您正在使用using):

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true));

将其更改为

System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true);

或完整代码,

System.IO.StreamWriter file;
foreach (BasicLog basicLog in emailAttach)
{
    file = new System.IO.StreamWriter(@"C:\\sorted.txt", true);
    file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}

或正确使用using

foreach (BasicLog basicLog in emailAttach)
{
    using(System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true))
    {
        file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
    }
}

答案 3 :(得分:2)

在写入文件之前,您正在处理StreamWriter。重构:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\\sorted.txt", true))   
{
   foreach (BasicLog basicLog in emailAttach)
   {     
      file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
   }
}