Convert File to Byte Array and Byte Array to Files

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; }
    }

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 ;
        }

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();

        }

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);
        }

Comments

Popular posts from this blog

SECURING WEBAPI USING JSON WEB TOKEN (JWT) IN WEB API C#

Adding ASP.NET MVC5 Identity Authentication to an existing project

Multiple model pass in MVC using tuple or Tuple in MVC