Search code examples
c#.netstreamruntime-errorfilestream

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


I am using the following code to write the length byte[] val to the end of a file and then write byte[] val itself

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);
}

And I get this Error on the last line of the using block:

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.

When I check the file I see that the stream didn't write the first 2 bytes at all, and this is the reason that the error occurs. Why is this happening?


Solution

  • The reason for the exception is that you're providing an offset where you shouldn't, as the exception message states.

    For any file length greater than zero, the first Write() will already throw, as the offset plus length will lie outside the len's bounds.

    The offset parameter denotes the offset in the byte array, which in both cases should be zero, as you want to write the entire array:

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

    If instead you want to append to the end of a file, see Append data to existing file in C#. If you want to start writing anywhere else, use Seek() to change the stream's position.