gpt4 book ai didi

c# - 无法写入已关闭的 TextWriter

转载 作者:行者123 更新时间:2023-11-30 18:52:55 25 4
gpt4 key购买 nike

我正在尝试将文本写入我的 txt 文件。第一次写应用程序崩溃并报错后

Cannot write to a closed TextWriter

我的列表包含浏览器打开的链接,我想将它们全部保存在 txt 文件中(如日志)。

我的代码:

FileStream fs = new FileStream(
"c:\\linksLog.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);

for (int i = 0; i < linksList.Count; i++)
{
try
{
System.Diagnostics.Process.Start(browserType, linksList[i]);
}
catch (Exception) { }

using (sw)
{
sw.WriteLine(linksList[i]);
sw.Close();
}

Thread.Sleep((int)delayTime);

if (!cbNewtab.Checked)
{
try
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName == getProcesses)
{
process.Kill();
}
}
}
catch (Exception) { }
}
}

最佳答案

您处于 for 循环中,但您在第一次迭代时关闭并处理了您的 StreamWriter:

using (sw)
{
sw.WriteLine(linksList[i]);
sw.Close();
}

相反,删除该 block ,并将所有内容包装在一个 using block 中:

using (var sw = new StreamWriter(@"C:\linksLog.txt", true)) {
foreach (var link in linksList) {
try {
Process.Start(browserType, list);
} catch (Exception) {}

sw.WriteLine(link);

Thread.Sleep((int)delayTime);

if (!cbNewtab.Checked) {
var processes = Process.GetProcessesByName(getProcesses);

foreach (var process in processes) {
try {
process.Kill();
} catch (Exception) {}
}
}
}
}

关于c# - 无法写入已关闭的 TextWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759445/

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