[C#] Writing Byte Array Data to a File (FileStream.Write)

When saving byte[] (byte array) data—such as image data, communication packets, or custom binary formats—as a file, using the FileStream class allows for flexible writing.

While there is a simple method called File.WriteAllBytes to write all bytes at once, using FileStream.Write enables detailed control. For example, you can write from the middle of an array, append to an existing file, or write while buffering.

目次

Implementation Sample: Saving Configuration Data as Binary

The following code prepares application configuration information as a string, converts it to byte data, and saves it using a file stream.

Sample Code

using System;
using System.IO;
using System.Text;

public class Program
{
    public static void Main()
    {
        // Destination file path
        string outputFile = "app_config.dat";

        // Data to write (example: configuration string)
        string configData = "Version=1.0;Mode=Secure;MaxUsers=100;";

        // Convert string to byte array (UTF-8)
        byte[] dataBuffer = Encoding.UTF8.GetBytes(configData);

        Console.WriteLine($"Write data size: {dataBuffer.Length} bytes");

        // Open (or create) a file using FileStream
        // FileMode.Create: Create a new file or overwrite if it exists
        // FileAccess.Write: Open with write-only access
        using (FileStream fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        {
            // Write the byte array to the file
            // Write(buffer, offset in array, number of bytes to write)
            fs.Write(dataBuffer, 0, dataBuffer.Length);
        }

        Console.WriteLine($"File saved successfully: {outputFile}");

        // (Verification) Read and display the file content
        if (File.Exists(outputFile))
        {
            string loadedText = File.ReadAllText(outputFile, Encoding.UTF8);
            Console.WriteLine($"\n[Verification] File Content: {loadedText}");
        }
    }
}

Execution Result

Write data size: 36 bytes
File saved successfully: app_config.dat

[Verification] File Content: Version=1.0;Mode=Secure;MaxUsers=100;

Explanation and Technical Points

1. FileStream.Write Method

public void Write(byte[] buffer, int offset, int count)

  • buffer: The byte array containing the data to be written.
  • offset: The zero-based index in the array from which to start writing.
  • count: The number of bytes to be written.

For example, if you want to skip the first 10 bytes of an array (perhaps a header) and write the rest, you can specify an offset. This is efficient because you do not need to create a copy of the array.

2. FileMode Choice

The behavior of the file depends on the FileMode specified in the FileStream constructor:

  • FileMode.Create: Creates a new file. If the file already exists, it is overwritten and the content is cleared.
  • FileMode.CreateNew: Creates a new file. If the file already exists, an error (exception) occurs.
  • FileMode.Append: Opens the file and moves to the end of the file to add data. If the file does not exist, it creates a new one.

It is important to select the correct mode for your specific use case.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次