如果您不想弄乱初始流中的数据,则不会像这样工作:
var myStreamInitially = new MemoryStream();
var myStreamClone = new MemoryStream();
myStreamInitially.CopyTo(myStreamClone);
var binaryWriteb = new BinaryWriter(myStreamClone);
如果您使用的是 .NET 4+,则 CopyTo 方法非常方便。
更新
这难道不是比更改 binaryStream 底层 baseStream 更安全吗:
void WriteToStreamInUnknownStatus(BinaryWriter binaryWriter)
{
var myStream = new MemoryStream();
try
{
binaryWriter.Write(myStream.ToArray());
}
catch
{ }
}
更新 2
如果你尝试这个,你会得到一个异常:“内存流不可解释”
static void Main(string[] args)
{
var binaryWrite = new BinaryWriter(new MemoryStream(new byte[] {1, 2, 3, 4}));
binaryWrite.Seek(3, SeekOrigin.Begin);
var position = binaryWrite.BaseStream.Position;
new MemoryStream(new byte[] {1, 2, 3, 4}).CopyTo(binaryWrite.BaseStream);
position = binaryWrite.BaseStream.Position;
}
因此,除了必须确保该属性是线程安全的之外,您还需要知道内部流的类型。冒着 IMO 的风险。