Reads a file into a byte array
//-----------------------------------------------------------------------
// <copyright file="Utilities.cs">
// Copyright (c) Andrew Arnott. All rights reserved.
// </copyright>
// <license>
// Microsoft Public License (Ms-PL http://opensource.org/licenses/ms-pl.html).
// Contributors may add their own copyright notice above.
// </license>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace LinqToTwitter
{
public static class Utilities
{
/// <summary>
/// Reads a file into a byte array
/// </summary>
/// <param name="filePath">Full path of file to read.</param>
/// <returns>Byte array with file contents.</returns>
public static byte[] GetFileBytes(string filePath)
{
byte[] fileBytes = null;
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var memStr = new MemoryStream())
{
byte[] buffer = new byte[4096];
memStr.Position = 0;
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStr.Write(buffer, 0, bytesRead);
}
memStr.Position = 0;
fileBytes = memStr.GetBuffer();
}
return fileBytes;
}
}
}
Related examples in the same category