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.

Step 1: Create an ASP.Net application and add a class Document.

public class Document    {
        public int DocId { get; set; }
        public string DocName { get; set; }
        public byte[] DocContent { get; set; }
    }


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.

public Document FileToByteArray(string fileName)        {
            byte[] fileContent = null;

            System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(fs);

            long byteLength = new System.IO.FileInfo(fileName).Length;
            fileContent = binaryReader.ReadBytes((Int32)byteLength);
            fs.Close();
            fs.Dispose();
            binaryReader.Close();
            Document = new Document();
            Document.DocName = fileName;
            Document.DocContent = fileContent;
            return Document ;
        }


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:

 

private void ShowDocument(string fileName, byte[] fileContent)

        {

            //Split the string by character . to get file extension type

            string[] stringParts = fileName.Split(new char[] { '.' });

            string strType = stringParts[1];

            Response.Clear();

            Response.ClearContent();

            Response.ClearHeaders();

            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);

            //Set the content type as file extension type

            Response.ContentType = strType;

            //Write the file content

            this.Response.BinaryWrite(fileContent);

            this.Response.End();

 

        }

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.

protected void Page_Load(object sender, EventArgs e)

        {

           FileToByteArray("C:\\Users\\santhosh.kumar\\Documents\\Test for rht format.rtf");

            ShowDocument(Document.DocName, Document.DocContent);

        }

For the complete source code, please find the attached solution.
 

Up Next
    Ebook Download
    View all
    Learn
    View all