C# 你能阻止 StreamReader 处理底层流吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1862261/
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-06 21:27:40  来源:igfitidea点击:

Can you keep a StreamReader from disposing the underlying stream?

c#file-io

提问by John Gietzen

Is there a way to do this:

有没有办法做到这一点:

this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);

using(var sr = new StreamReader(this.logFile))
{
    // Read the data in
}

// ... later on in the class ...

this.logFile = File.Open("what_r_u_doing.log", FileMode.OpenOrCreate, FileAccess.ReadWrite);

using(var sw = new StreamWriter(this.logFile))
{
    // Write additional data out...
}

Without having to open the file twice?

无需打开文件两次?

I can't seem to make the StreamReader not-dispose my stream. I don't want to just let it go out of scope, either. Then the garbage collector will eventually call the Dispose, killing the stream.

我似乎无法让 StreamReader 不处理我的流。我也不想让它超出范围。然后垃圾收集器最终会调用 Dispose,杀死流。

采纳答案by Mehrdad Afshari

I don't want to just let it go out of scope, either. Then the garbage collector will eventually call the Dispose, killing the stream.

我也不想让它超出范围。然后垃圾收集器最终会调用 Dispose,杀死流。

Garbage collector will call the Finalizemethod (destructor), not the Disposemethod. The finalizer will call Dispose(false)which will notdispose the underlying stream. You should be OK by leaving the StreamReadergo out of scope if you need to use the underlying stream directly. Just make sure you dispose the underlying stream manually when it's appropriate.

垃圾收集器会调用Finalize方法(析构函数),而不是Dispose方法。终结器将调用Dispose(false)不会处置底层流。StreamReader如果您需要直接使用底层流,您应该可以离开超出范围。只要确保在适当的时候手动处理底层流。

回答by Mike Atlas

Close it yourself in a try/finallyclause when you're done with it.

完成后用try/finally子句自己关闭它。

var sr = new StreamReader();
try {
    //...code that uses sr
    //....etc
}
finally
{
    sr.Close();
}

回答by eWolf

Just remove the using-Block. You don't have to Dispose() the StreamReader if you don't want to do Dispose() the stream, I think.

只需删除 using-Block。我认为,如果您不想对流进行 Dispose(),则不必对 StreamReader 进行 Dispose()。

回答by Thomas Levesque

You could use the NonClosingStreamWrapperclass from Jon Skeet's MiscUtil library, it serves exactly that purpose

您可以使用NonClosingStreamWrapperJon Skeet 的MiscUtil 库中的类,它正是用于此目的

回答by Aaron

You could create a new class which inherits from StreamReader and override the Close method; inside your Close method, call Dispose(false), which as Mehrdad pointed out, does not close the stream. Same applies to StreamWriter, of course.

您可以创建一个继承自 StreamReader 并覆盖 Close 方法的新类;在您的 Close 方法中,调用 Dispose(false),正如 Mehrdad 指出的那样,它不会关闭流。当然,这同样适用于 StreamWriter。

However, it seems like a better solution would simply be to hold onto the StreamReader and StreamWriter instances as long as you may need them. If you're already planning to keep the stream open, you might as well keep a StreamReader and StreamWriter open also. If you use StreamWriter.Flush and Stream.Seek correctly, you should be able to make this work even when doing both reading and writing.

但是,似乎更好的解决方案是只要您可能需要它们就保留 StreamReader 和 StreamWriter 实例。如果您已经计划保持流打开,您也可以保持 StreamReader 和 StreamWriter 也打开。如果您正确使用 StreamWriter.Flush 和 Stream.Seek,即使在进行读取和写入时,您也应该能够完成这项工作。

回答by Simon Buchan

.NET 4.5 will finally fix this problem with a new constructors on StreamReader and StreamWriter that take a leaveOpen parameter:

.NET 4.5 最终将通过在 StreamReader 和 StreamWriter 上使用 leaveOpen 参数的新构造函数来解决这个问题:

StreamReader(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen)

StreamWriter(Stream stream, System.Text.Encoding encoding, int bufferSize, bool leaveOpen)

回答by HANiS

Use another constructor overload where you can specifu a "leaveOpen" parameter to "true"

使用另一个构造函数重载,您可以将“leaveOpen”参数指定为“true”

回答by Nick N.

I always use something like this: (it also uses the leaveOpenargument)

我总是使用这样的东西:( 它也使用leaveOpen参数)

public static class StreamreaderExtensions
{
    public static StreamReader WrapInNonClosingStreamReader(this Stream file) => new StreamReader(file, Encoding.UTF8, true, 1024, true);
}

Usage:

用法:

using (var reader = file.WrapInNonClosingStreamReader())
{
     ....
}