gpt4 book ai didi

c# - 如何在 .NET 中将 StreamWriter 的源设置为多个?

转载 作者:行者123 更新时间:2023-11-30 20:39:51 24 4
gpt4 key购买 nike

我正在用 .NET 开发一些网络程序。我想在我的输出窗口上看到整个文本流作为日志。所以我试图搜索在 StreamWriter 上设置多个源的解决方案。但我找不到。我想要像下面这样的样式而不是扩展方法:

var sw = new StreamWriter(socketStream, traceStream)

var sw = new StreamWriter(socketStream);
sw.setSecondStream(traceStream);

最佳答案

制作分流器应该不难。对于没有 Seek 函数的只写流,它非常简单。

构造函数调用看起来像

var sw = new StreamWriter(new WriteStreamSplitter(socketStream, traceStream));

和类(class)(未经测试,只是一个模型)

class WriteStreamSplitter : Stream
{
public WriteStreamSplitter(Stream a, Stream b)
{
_streamA = a;
_streamB = b;
}

public override void Write(byte[] buffer, int offset, int count)
{
_streamA.Write(buffer, offset, count);
_streamB.Write(buffer, offset, count);
}

public override bool CanWrite { get { return true; } }
public override bool CanRead { get { return false; } }

// trivial overloads of all other abstract members,
// they are allowed to throw NotImplemented


protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
// Maybe it's best to do nothing here but a StreamWriter
// assumes 'ownership' of the wrapped stream,
// so if we want to continue that pattern:

// the guidelines say these shouldn't throw
_streamA.Dispose();
_streamB.Dispose();
}
}
}

关于c# - 如何在 .NET 中将 StreamWriter 的源设置为多个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33935411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com