FileStream"无法访问已关闭的文件"

iNe*_*elp 7 c# filestream

为什么我在使用时收到上述错误消息using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write))但是当我用它替换它时程序执行得很好fileStream = File.Create(path);

我想将控制台输出附加到外部文件.这是我的代码:

 //copy console output to file in bin\Debug folder
    class ConsoleCopy : IDisposable
    {
        FileStream fileStream;
        StreamWriter fileWriter;
        TextWriter doubleWriter;
        TextWriter oldOut;
        class DoubleWriter : TextWriter
        {
            TextWriter one;
            TextWriter two;
            public DoubleWriter(TextWriter one, TextWriter two)
            {
                this.one = one;
                this.two = two;
            }
            public override Encoding Encoding
            {
                get { return one.Encoding; }
            }
            //Clears all buffers for the current writer
            public override void Flush()
            {
                one.Flush();

                two.Flush();
            }
            public override void Write(char value)
            {
                **one.Write(value);**//error thrown here
                two.Write(value);
            }
        }
        public ConsoleCopy(string path)
        {
            oldOut = Console.Out;
            try
            {
                **//fileStream = File.Create(path);** //runs alright with this line
                fileWriter = new StreamWriter(fileStream);
                fileWriter.AutoFlush = true;
                doubleWriter = new DoubleWriter(fileWriter, oldOut);
            }
            catch (Exception e)
            {
                Console.WriteLine("Cannot open file for writing");
                Console.WriteLine(e.Message);
                return;
            }
            Console.SetOut(doubleWriter);
        }
        public void Dispose()
        {
            Console.SetOut(oldOut);
            if (fileWriter != null)
            {
                fileWriter.Flush();
                fileWriter.Close();
                fileWriter = null;
            }
            if (fileStream != null)
            {
                fileStream.Close();
                fileStream = null;
            }
        }
    }//end of consoleCopy
Run Code Online (Sandbox Code Playgroud)

我在我的main方法中调用此方法:

 //pass output to ConsoleCopy method for copying to .txt file
        using (var cc = new ConsoleCopy("mylogfile.txt"))
        {
           DateTime theDate = DateTime.UtcNow;

            string custom = theDate.ToString("d");

            Console.WriteLine("User has logged in on " + custom);
        }
Run Code Online (Sandbox Code Playgroud)

更新:

此错误先前显示在one.Write(value).感谢彼得,我设法解决了这个问题.感谢大家的贡献和帮助:)

Pet*_*Luu 7

编辑:如果你在写之前得到它,那是因为我误读了这个问题并将using语句放在ConsoleCopy构造函数中意味着当ConsoleCopy完成创建时,FileStream就会被关闭.当你尝试写它时,因为它已经被关闭了你得到了那个例外.应用相同的解决方案 - 保持FileStream打开并在Dispose()中关闭它,它应该与main方法中的using语句一起使用.

如果我理解正确,你可以处理这个例外,对吗?如果是这样,那是因为正在发生的事情本质上就是你要关闭那个流两次.

using (var cc = new ConsoleCopy("mylogfile.txt"))
{
    // At this time, your filestream is created with the using statement.
    // Writing happens here.
    // Your filestream is closed at the end of the using statement inside of the ConsoleCopy constructor.
} 
// At this point, ConsoleCopy tries to call Dispose(), which flushes and closes everything again. However, this throws an exception because the using statement already closed the FileStream.
Run Code Online (Sandbox Code Playgroud)

如果您的目标是追加到文件的末尾并且Dispose()方法在内部关闭所有内容,那么为什么不直接替换

**//fileStream = File.Create(path);** //runs alright with this line
Run Code Online (Sandbox Code Playgroud)

fileStream = File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
Run Code Online (Sandbox Code Playgroud)

让你的main中的using语句在内部为你关闭流?