我正在尝试将文本写入txt文件。第一次写入后,应用程序崩溃并出现错误
无法写入关闭的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();
}
相反,删除该块,并将所有内容包装在一个using
块中:
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) {}
}
}
}
}
行
using (sw)
关闭/配置StreamWriter
。
由于正在循环,所以要处置已经处置的StreamWriter
。
在完成所有写操作之后,更好地关闭StreamWriter
outside循环。
此外,捕获异常并忽略捕获的异常几乎总是一个坏主意。如果您无法处理异常,请不要捕获它。
问题是您正在循环中关闭Stream,应仅在...之后执行]
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)
{
}
// Removed the using blocks that closes the stream and placed at the end of loop
sw.WriteLine(linksList[i]);
Thread.Sleep((int)delayTime);
if (!cbNewtab.Checked)
{
try
{
foreach (Process process in Process.GetProcesses())
{
if (process.ProcessName == getProcesses)
{
process.Kill();
}
}
}
catch (Exception)
{ }
}
}
sw.Close();
这是因为,实际上,您正在循环的中间关闭流。您在中间有using (sw)
块,在通过for
循环的第一次运行中可以正常工作,然后崩溃。要解决此问题,只需删除sw.Close()
调用,然后将using
移到for
循环之外即可:
不要在代码中写sw.Close()
,因为如果关闭文件,代码将无法读取文件。