编辑:如果您在编写之前得到它,那么这是因为我误读了问题并将 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
with
fileStream = File.Open(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
并让 main 中的 using 语句为您在内部关闭流?