Skip to main content

C# function to write an array of bytes to the file system.

/// <summary>
/// Writes the specified <paramref name="bytes"/> to the file system.
/// If the file already exists, it will be overwritten.
/// </summary>
/// <param name="bytes">The bytes to write.</param>
/// <param name="filePath">The file path.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="filePath"/> or <paramref name="bytes"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">Thrown if <paramref name="filePath"/> is <c>null</c> or contains whitespace only characters.</exception>
public static void WriteBytesToFile(byte[] bytes, string filePath)
{
    if (bytes == null)
    {
        throw new ArgumentNullException(nameof(bytes));
    }

    if (filePath == null)
    {
        throw new ArgumentNullException(nameof(filePath));
    }

    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentException("File path cannot be only whitespace characters.", nameof(filePath));
    }

    using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {
        fs.Write(bytes, 0, bytes.Length);
    }
}