How to generate a binary file? C#

ale picture ale · Apr 18, 2011 · Viewed 6.9k times · Source

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

Answer

ICR picture ICR · Apr 18, 2011

As it is it should work fine. Here is a refactored version, you can pick and choose which bits of the refactoring you like.

public void WriteFrameCodesAsBinary(IEnumerable<int> frameCodes)
{
    using (FileStream fileStream = new FileStream(binaryFilePath,  FileMode.Create))
    using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
    {
        foreach (int frameCode in frameCodes) {
            binaryWriter.Write(frameCode);
        }
    }
}

I would rename the function to describe the action it will do. FrameCodesBinaryWriter sounds more like a class name to me.

If you don't need the ordering of the List<T>, it might be an idea to accept an IEnumerable<T> instead. That way you can be more flexible about what you pass in.

Some people like to stack their using statements to remove a layer of nesting (code indentation). Personally I'm not a massive fan of this, but it's a matter of personal taste and style.

Using an IEnumerable<T> forces us to use foreach, but even with List<T> it can look cleaner/make it more obvious you are iterating through the list.

As previously mentioned, if you are using using you don't need to explicitly close the binary writer - that will be done automatically when the using block is exited.