2012-03-19 115 views
2

basicLog是名称和时间戳列表。我想将它们写入文件。我得到的两个错误是';'在StreamWriter行和'文件'上。在第二行。C#StreamWriter未写入文件

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

该文件被创建得很好,但没有任何被写入它。我对当前上下文中不存在的文件感到困惑,因为它在创建之前就已经存在。感谢您的任何帮助。

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"); 
} 
+1

['using'声明(C#参考)](http://msdn.microsoft.com/en-us/library/yh598w02。 aspx) – tcovo 2012-03-19 14:41:00

回答

4

哎呀有在使用线的端部的分号???

也许你的意图是:

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

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"); 
    } 
} 
+0

最好删除分号而不是使用分号。使用放在这里 – Archeg 2012-03-19 14:40:42

+0

@Archeg这个人是*不*有一个备用分号,他有一个*错位*一个,现在去和他解释一下。事情是他正在误用'using'指令 – Shai 2012-03-19 14:41:58

+0

@Archeg是对的。如果打开文件时不使用'使用',并且存在例外,则该文件将保持打开状态,并具有所有可能的相关问题 – MiMo 2012-03-19 14:43:53

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"); 
    } 
} 
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()的控制下。 {}使这更清晰。

这将工作,但要注意,它是非常低效的,你重新打开文件(为append)多次。

因此,最好是使用以反转的foreach /:

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"); 
    } 
} 
相关问题