gpt4 book ai didi

C# StreamWriter 不写入文件

转载 作者:行者123 更新时间:2023-11-30 19:02:42 27 4
gpt4 key购买 nike

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

最佳答案

是的,你确实有一个错误的空语句。

去掉';'并缩进以说明原因:

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() 的控制之下。 {} 使这一点更加清晰。

这会起作用,但请注意它非常低效,您要多次重新打开文件(用于追加)。

所以最好反转 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");
}
}

关于C# StreamWriter 不写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com