C# 无法写入关闭的 TextWriter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9759445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:44:46  来源:igfitidea点击:

Cannot write to a closed TextWriter

c#text-filestextwriter

提问by user1269592

I am trying to write text to my txt file. After the first write the application crash with error

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

Cannot write to a closed TextWriter

无法写入关闭的 TextWriter

My list contains links that the browser opens and I want to save all of them in txt file (like a log).

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

My code:

我的代码:

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) { }
    }
}

采纳答案by Ry-

You're in a forloop, but you close and dispose of your StreamWriteron the first iteration:

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

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

Instead, remove that block, and wrap everything in one usingblock:

相反,删除该块,并将所有内容包装在一个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) {}
            }
        }
    }
}

回答by Arnaud F.

The problem is that you are closing you Stream in the loop, should done only after...

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

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();

回答by Uwe Keim

The line

线

using (sw)

closes/disposes your StreamWriter.

关闭/处理您的StreamWriter.

Since you are looping, you dispose an already disposed StreamWriter.

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

Better to close the StreamWriteroutsidethe loop, after all write operations are finished.

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

In addition, catching exceptions and ignoring the caught exception is almost always a bad idea. If you can't handle an exception, do not catch it.

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

回答by Avner Shahar-Kashtan

That's because you are, indeed, closing your stream in the middle of the loop. You have the using (sw)block in the middle, which will work fine in the first run through the forloop, and then crash. To fix it, just drop the sw.Close()call, and move the usingto be outside the forloop:

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

回答by Arshiya

Dont write the sw.Close()in your code because if the file is closed the code cannot read the file.

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