问题描述
我的根本问题是,当 using 在 StreamWriter 上调用 Dispose 时,它也会处理 BaseStream (Close 也有同样的问题).
My root problem is that when using calls Dispose on a StreamWriter, it also disposes the BaseStream (same problem with Close).
我有一个解决方法,但如您所见,它涉及复制流.有没有办法在不复制流的情况下做到这一点?
I have a workaround for this, but as you can see, it involves copying the stream. Is there any way to do this without copying the stream?
这样做的目的是将一个字符串的内容(最初是从数据库中读取的)获取到一个流中,以便第三方组件可以读取该流.
注意:我无法更改第三方组件.
The purpose of this is to get the contents of a string (originally read from a database) into a stream, so the stream can be read by a third party component.
NB: I cannot change the third party component.
public System.IO.Stream CreateStream(string value)
{
var baseStream = new System.IO.MemoryStream();
var baseCopy = new System.IO.MemoryStream();
using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
{
writer.Write(value);
writer.Flush();
baseStream.WriteTo(baseCopy);
}
baseCopy.Seek(0, System.IO.SeekOrigin.Begin);
return baseCopy;
}
用作
public void Noddy()
{
System.IO.Stream myStream = CreateStream("The contents of this string are unimportant");
My3rdPartyComponent.ReadFromStream(myStream);
}
理想情况下,我正在寻找一种名为 BreakAssociationWithBaseStream 的虚构方法,例如
Ideally I'm looking for an imaginary method called BreakAssociationWithBaseStream, e.g.
public System.IO.Stream CreateStream_Alternate(string value)
{
var baseStream = new System.IO.MemoryStream();
using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
{
writer.Write(value);
writer.Flush();
writer.BreakAssociationWithBaseStream();
}
return baseStream;
}
推荐答案
如果您使用的是 .NET Framework 4.5 或更高版本,则有一个 StreamWriter 重载使用它您可以在编写器关闭时要求基本流保持打开状态.
If you are using .NET Framework 4.5 or later, there is a StreamWriter overload using which you can ask the base stream to be left open when the writer is closed.
在 .NET Framework 4.5 之前的早期版本中,StreamWriter 假定它拥有流.选项:
In earlier versions of .NET Framework prior to 4.5, StreamWriter assumes it owns the stream. Options:
- 不要处理
StreamWriter;只需冲洗它. - 创建一个流包装器,它忽略对
Close/Dispose的调用,但代理其他所有内容.如果你想从那里获取它,我在 MiscUtil 中有一个实现.莉>
- Don't dispose the
StreamWriter; just flush it. - Create a stream wrapper which ignores calls to
Close/Disposebut proxies everything else along. I have an implementation of that in MiscUtil, if you want to grab it from there.
这篇关于有没有办法在不关闭其 BaseStream 的情况下关闭 StreamWriter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)