Tuesday, April 6, 2010

How to convert FileStream to MemoryStearm?

We do require sometime to convert a FileStream to MemoryStream. This is basically needed you need to download an existing file from the file system.
Steps:

//Open the File into file stream
FileStream fileStream = new FileStream(Server.MapPath(fileName), FileMode.Open, FileAccess.Read, FileShare.Read);

//Create and populate a memorystream with the contents of the filestream object

private MemoryStream StreamToMemory(FileStream fileStream)
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.SetLength(fileStream.Length);
fileStream.Read(memoryStream.GetBuffer(), 0, (int)fileStream.Length);


memoryStream.Flush();
fileStream.Close();
memoryStream.Close();
return memoryStream;


}
// Download the file at client end

byte[] byteArray = mstream.ToArray();
mstream.Flush();


mstream.Close();
Response.Clear();


Response.BinaryWrite(byteArray);
Response.AddHeader("Content-Disposition", "attachment; filename=QatargasTimesheet.xls");
Response.AddHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";

No comments:

Post a Comment