Photo Gallery

Friday, July 7, 2017

Read input file and return as a byte array C#



In this post  I will explain how to read the input file and return content of that file as a byte array.
Note: you can store byte array into database as a BLOB into VARBINARY or IMAGE field.

Method to read file and return byte array.

/// <summary>
/// Method to read a file and return byte array.
/// </summary>
/// <param name="fullFilePath">The input file to read.</param>
/// <returns>The byte array representing the file contents.</returns>
public static byte[] GetBytesFromFile(string fullFilePath)
{
byte[] bytes = null;
FileStream fs = null;
try
{
fs = File.OpenRead(fullFilePath);
bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
}
catch (Exception exc)
{
string msg = string.Format("Exception reading file {0}", fullFilePath);
// Logged the exception
}
finally
{
if (fs != null)
{
fs.Close();
}
}
return bytes;
}
view raw Utility.cs hosted with ❤ by GitHub

You are done.

If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below. Thank you !!!

No comments:

Post a Comment