3

我正在尝试将文本写入我的 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) { }
    }
}
4

5 回答 5

13

您处于一个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) {}
            }
        }
    }
}
于 2012-03-18T15:21:02.397 回答
3

线

using (sw)

关闭/处置您的StreamWriter.

由于您正在循环,因此您处置了一个已经处置的StreamWriter.

最好在所有写操作完成后关闭StreamWriter 外部循环。

此外,捕获异常并忽略捕获的异常几乎总是一个坏主意。如果您无法处理异常,请不要捕获它。

于 2012-03-18T15:21:13.023 回答
2

问题是你正在循环中关闭你的流,应该只在......

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();
于 2012-03-18T15:20:43.987 回答
1

那是因为您确实在循环中间关闭了流。您using (sw)在中间有块,它在第一次运行for循环时可以正常工作,然后崩溃。要修复它,只需挂断sw.Close()电话,并将 移动usingfor循环之外:

于 2012-03-18T15:21:41.817 回答
0

不要sw.Close()在代码中写入,因为如果文件关闭,代码将无法读取文件。

于 2012-03-18T15:25:12.273 回答