Convert File to Byte Array and Byte Array to Files

In this article, let us see how to convert a file content to a byte array and restore the original content from the byte array and display it in its original file format such as pdf, doc, xls, rtf, jpeg, png etc.

Convert a file content to a byte array

Step 1: Create an ASP.Net application and add a class Document.
  1. public class Document  
  2. {  
  3.     public int DocId { getset; }  
  4.     public string DocName { getset; }  
  5.     public byte[] DocContent { getset; }  
  6. }
Step 2: Create a file of format doc/pdf/rtf etc. and convert the file content to a ByteArray using the following method. Then create an object of type Document and assign the Docname and DocContent property values from filename and filecontent.
  1. public Document FileToByteArray(string fileName)  
  2. {  
  3.     byte[] fileContent = null;  
  4.     System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);  
  5.     System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);  
  6.     long byteLength = new System.IO.FileInfo(fileName).Length;  
  7.     fileContent = binaryReader.ReadBytes((Int32)byteLength);  
  8.     fs.Close();  
  9.     fs.Dispose();  
  10.     binaryReader.Close();  
  11.     Document = new Document();  
  12.     Document.DocName = fileName;  
  13.     Document.DocContent = fileContent;  
  14.     return Document;  
  15. }  

Convert a byte array to file content

Step 3: Now we need to convert the byte array back again to the file content and display it to the user with download options. For that I am using another method, ShowDocument, as below: 
  1. private void ShowDocument(string fileName, byte[] fileContent)  
  2. {  
  3.     //Split the string by character . to get file extension type  
  4.     string[] stringParts = fileName.Split(new char[] { '.' });  
  5.     string strType = stringParts[1];  
  6.     Response.Clear();  
  7.     Response.ClearContent();  
  8.     Response.ClearHeaders();  
  9.     Response.AddHeader("content-disposition""attachment; filename=" + fileName);  
  10.     //Set the content type as file extension type  
  11.     Response.ContentType = strType;  
  12.     //Write the file content  
  13.     this.Response.BinaryWrite(fileContent);  
  14.     this.Response.End();  
  15. } 
Step 4: In the page_load event, I have the following code, which will read the contents from the file and convert it to a ByteArray using the FileToByteArray method and convert it back to content using the ShowDocument method.

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     FileToByteArray("C:\\Users\\santhosh.kumar\\Documents\\Test for rht format.rtf");  
  4.     ShowDocument(Document.DocName, Document.DocContent);  
  5. }
For the complete source code, please find the attached solution.