FileStream“无法访问已关闭的文件”

时间:2015-04-14 00:35:13

标签: 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

我在我的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);
        }

更新:

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

2 个答案:

答案 0 :(得分:6)

编辑:如果您在编写之前获得它,那么它是因为我误读了问题并将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.

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

**//fileStream = File.Create(path);** //runs alright with this line

fileStream = File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);

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

答案 1 :(得分:1)

您是否在using语句之外运行写代码?您可能在使用它之前关闭流。

运行时会发生什么:

using (fileStream = new FileStream(path, FileMode.Append, FileAccess.Write))
{
  fileWriter = new StreamWriter(fileStream);
  fileWriter.AutoFlush = true;
  doubleWriter = new DoubleWriter(fileWriter, oldOut);
}