Sunday, August 5, 2012

How to convert a file to byte array and create file from byte array?

Problem:
How to convert a file to byte array? and how can I create the file from byte array?

Solution:

To convert a file to byte array you need to used FileStream class. You have to open instance of the class in read mode and class Read() method to read bytes in byte array.

To retrieve the file from byte array you have to open the instance of the class in create mode with write access and call Write() method to write bytes and create file.

Look at following code example:


string sessionId = Session.SessionID;
        imgDocImage.ImageUrl = string.Empty;
        string fileName = hdfImagePath.Value.ToString();
        string docDtlId = hfDoctDtlId.Value.ToString();
        string tempPath = Server.MapPath("~/Uploads");
        tempPath = tempPath + "\\" + sessionId + "\\" + fileName;
        string newPath = Server.MapPath("~/Uploads");
        newPath = newPath + "\\" + docDtlId;
        if (!System.IO.Directory.Exists(newPath))
        {
            System.IO.Directory.CreateDirectory(newPath);
        }
        newPath = newPath + "\\" + fileName;
        int id = 0;
        if (!System.IO.File.Exists(newPath))
        {
            FileStream fsr = new FileStream(tempPath, FileMode.Open, FileAccess.Read);
            int bytesInFile = (int)fsr.Length;
            byte[] fileContent = new byte[bytesInFile];
            long bytesRead = fsr.Read(fileContent, 0, bytesInFile);
            fsr.Close();

            FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
            fs.Write(fileContent, 0, fileContent.Length);
            fs.Close();
        }

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete