我有一些使用第三方库 EDIFabric 的代码,它写入流,我需要捕获该输出并使用它通过 StreamReader 返回字符串。
// Build out the memory stream we'll use to conver to a string.
using (var stream = new MemoryStream())
{
using (var writer = new X12Writer(stream))
{
writer.Write("Write EDI values to the stream"); // Not valid EDI output...
writer.Flush();
// Flush() is obsolete and generates a CS0618 compiler warning, "Type or member is obsolete"
stream.Seek(0, SeekOrigin.Begin); // Return to the beginning of the stream
}
using StreamReader reader = new(stream);
// If I omit the flush, the returned string is empty
return reader.ReadToEnd(); // Returns the stream as a string
}
有什么不包括使用 Flush() 的建议吗?
您无法从将其更改提交到流的流实用程序编写器(对于该流)读取数据。一些写入器允许在任何点提交所有缓冲的数据,但不是全部 - 通常写入器支持的数据格式需要特定的块大小或一些其他限制,限制可以将多少部分数据写入流。
如果您需要获取完整的数据 - 您最安全的选择是处理编写器并寻找要启动的流(如问题中的代码所示)或在相同的数据上创建一个新流(编写器不需要支持“离开据我所知,溪流开放”)。我对
X12Writer
类一无所知,但由于上述原因,他们可能不希望有人调用 Flush
,并且应该立即提交整个流以产生有效的结果。
// re-creating a stream from a disposed memory stream.
var freshStream = new MemoryStream(srteam.ToArray());
如果您对部分数据感到满意 - 请查看有关“C# tee 流”的问题,例如 将文件重定向到流 C# 以在数据提交到流时捕获数据。