Skip to main content

Optimally read the entire file contents into a byte array, without any sort of file locking or access restrictions placed on the source file.

/// <summary>
/// Optimally read the entire file contents into a byte array, without any sort of file locking
/// or access restrictions placed the source file.
/// </summary>
/// <param name="path">The source file path.</param>
/// <returns>A byte array comprised of the entire file contents.</returns>
public static byte[] ReadAllFileBytes(string path)
{
    using (var content = new MemoryStream())
    {
        using (var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            const int bufferSize = 4096;

            var buffer = new byte[bufferSize];
            var read = stream.Read(buffer, 0, bufferSize);

            while (read > 0)
            {
                content.Write(buffer, 0, read);
                read = stream.Read(buffer, 0, bufferSize);
            }
        }

        return content.ToArray();
    }
}