PDFsharp & MigraDoc Foundation
http://forum.pdfsharp.com/

PdfDocumentRenderer.Save() exclusive lock?
http://forum.pdfsharp.com/viewtopic.php?f=2&t=2782
Page 1 of 1

Author:  vence [ Thu Apr 03, 2014 3:05 pm ]
Post subject:  PdfDocumentRenderer.Save() exclusive lock?

Hi All,

It seems that the PdfDocumentRenderer.Save() does not stop others processes reading the file while it writes the file to disk, thus if you have another process which is simply moving files (File.Copy()) the PDF file can be copied regardless it is stated and it could be corrupted.

I would just like to ask for confirmation (I tend to put an exclusive lock when writing a file) and how I could work around this.

Code:
  Document doc = Documents.CreateResultDocument(data);
  //Create a renderer for PDF that uses Unicode font encoding
  PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);
 //Set the MigraDoc document
  pdfRenderer.Document = doc;
  //Create and save the PDF document
   pdfRenderer.RenderDocument();
   log.Info("Saving PDF for file: " + originalFilename + " ...");
   pdfRenderer.Save(outputFilename);
   log.Info("PDF for file: " + originalFilename + " has been created => " + outputFilename);


Many thanks

Author:  Thomas Hoevel [ Thu Apr 03, 2014 3:31 pm ]
Post subject:  Re: PdfDocumentRenderer.Save() exclusive lock?

Hi!

Here's what Save(string) does internally:
Code:
Stream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
Save(stream);
.NET allows read access for files created this way.

Solution: create a stream with appropriate permissions and use Save(stream, true) instead.

Author:  vence [ Fri Apr 04, 2014 7:35 am ]
Post subject:  Re: PdfDocumentRenderer.Save() exclusive lock?

Thanks Thomas,

Code:
  //Create stream with exclusive locks thus nobody can access the file until it has been written
   Stream stream = new FileStream(outputFilename, FileMode.Create, FileAccess.Write,FileShare.None);
   log.Info("Saving PDF for file: " + originalFilename + " ...");
   pdfRenderer.Save(stream, true);
   log.Info("PDF for file: " + originalFilename + " has been created => " + outputFilename);

Author:  Thomas Hoevel [ Mon Apr 07, 2014 10:12 am ]
Post subject:  Re: PdfDocumentRenderer.Save() exclusive lock?

Hi, Vence,

thanks for the feedback.

@All: future versions of PDFsharp and MigraDoc will open the file internally with "FileShare.None" because it makes no sense to allow read access to a partially written PDF file.

When a constructor with fewer parameters is used, one should always check the default values of the missing parameters ... :wink:

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/