Search code examples
c#binaryfilesbinarywriter

How to generate a binary file? C#


I need to make a method that generates a binary (4 bytes long), receives List of integers and writes this List one by one in the file. So, I have this:

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

is this correct? or some other solution please


Solution

  • You don't need to close binaryWriter because you have a using clause anyway. binaryFilePath needs to be a field of the class, apart from that it looks ok.