使用 System.IO.Stream C# 写入文件时文件不更新

File doesn't update when writing to it using System.IO.Stream C#

我正在使用以下代码将长度 byte[] val 写入文件末尾,然后写入 byte[] val 本身

byte[] len = BitConverter.GetBytes((UInt16) val.Length);
int fileLen = (int)new FileInfo(filePath).Length;
using (Stream stream = File.OpenWrite(filePath))
{
    stream.Write(len, fileLen, 2);
    stream.Write(val, fileLen + 2, val.Length);
}

我在 using 块的最后一行收到此错误:

Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.

当我检查文件时,我发现流根本没有写入前 2 个字节,这就是发生错误的原因。为什么会这样?

出现异常的原因是您在不应该提供的地方提供了偏移量,如异常消息所述。

对于任何大于零的文件长度,第一个 Write() 已经抛出,因为偏移量加上长度将位于 len 的范围之外。

offset 参数表示字节数组中的偏移量,在两种情况下都应为零,因为您要写入整个数组:

stream.Write(len, 0, len.Length);
stream.Write(val, 0, val.Length);

如果您想要附加到文件末尾,请参阅 Append data to existing file in C#。如果您想在其他任何地方开始写作,请使用 Seek() 更改流的位置。