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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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; | |
} |
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