我应该在 Stream.CopyTo 之前使用 Stream.Flush 吗?

Should I use Stream.Flush before Stream.CopyTo?

我有 MemoryStream,我正在使用 StreamWriter 填充一些数据。 最后我想把它转储到不同的流(不总是文件)。

我应该在使用 Steram.CopyTo 方法之前调用 Stream.Flush 吗?

Should I call Stream.Flush before using Stream.CopyTo method?

不,不需要调用 Flush。但是,您需要在 MemoryStream.

上将 Position 重置为 0

CopyTo 文档说:

Copying begins at the current position in the current stream, and does not reset the position of the destination stream after the copy operation is complete.

您永远不需要在内存流上调用 Flush,因为该操作不执行任何操作。如果查看源代码,实现是空的。您确实需要在写入后倒回流。

但是,您需要刷新 StreamWriter,以确保在开始复制之前所有数据都被推入内存流。

您可以将此模式与 StreamWriter 写入内存流一起使用以避免显式刷新:

MemoryStream memStream = ...
using (StreamWriter wr = new StreamWriter(memStream)) {
    ... // Do the writing
}
memStream.Position = 0; // Rewind
// At this point `memStream` has all data pushed into it,
// and is positioned at zero, so it's ready to be copied.