Thursday 6 March 2014

Save PDF file to local disk using MemoryStream

I found difficulty in saving a PDF file  to my local hard disk using a MemoryStream. Tried some ways and resulted with some errors like "Access is denied.","Cannot write as stream is in use.","There was an error in opening the document.As the document is already open or is in use."

I am sharing you the simple one line code which will over cross all these errors and you can save the file.

using (var stream = new MemoryStream())
{
    //Generate PDF bytes here using stream
    bytes = stream.ToArray();
    var fullpath = Path.Combine(@"C:\DestinationFolder", "PDFName");
    System.IO.File.WriteAllBytes(fullpath, bytes);
}