Search code examples
c#binaryfilesbinarywriter

How Write a List<int> to binary file (4 bytes long)?


I need to write a List of ints to a binary file of 4 bytes in length, so, I need to make sure that the binary file is correct, and I do the following:

using (FileStream fileStream = new FileStream(binaryFileName, FileMode.Create)) // destiny file directory.
{
  using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
  {
    for (int i = 0; i < frameCodes.Count; i++)
    {
      binaryWriter.Write(frameCodes[i]);
      binaryWriter.Write(4);
    }
    binaryWriter.Close();
  }
}

at this line: binaryWriter.Write(4); I give the size, is that correct?


Solution

  • at this line "binaryWriter.Write(4);" I give the size, that's correct??

    No, it's not correct. The line binaryWriter.Write(4); will write the integer 4 into the stream (e.g. something like 00000000 00000000 00000000 00000100).

    This line is correct: binaryWriter.Write(frameCodes[i]);. It writes the integer frameCodes[i] into the stream. Since an integer requires 4 bytes, exactly 4 bytes will be written.

    Of course, if your list contains X entries, then the resulting file will be of size 4*X.