1
PD4ML pd4ml = new PD4ML();
pd4ml.enableTableBreaks(true);
pd4ml.PageInsets = new System.Drawing.Rectangle(5, 5, 5, 5);
pd4ml.PageSize = PD4Constants.getSizeByName("LETTER");
Byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream stream = new MemoryStream(byteArray);

FinalPath = FinalPath + @"\" + VersionID;
        if (!Directory.Exists(FinalPath))
            Directory.CreateDirectory(FinalPath);

string FileName = FinalPath +FileName+ ".pdf";

pd4ml.render(stream,new System.IO.FileStream(FileName, System.IO.FileMode.CreateNew));        
stream.Flush();
stream.Close();
stream.Dispose();

//In another method I'm opening this file
File stream fs = File.Open(path, FileMode.Open, FileAccess.Read);`

I'm generating PDF using pd4ml.render() method. When I create this file using render method it is opened somewhere in system internally. That's why when I tried to open it mannualy using Filestream fs=new Filestream(path,FileMode.Open,FileAccess.Read)

It throws and exception of file is being used by another process. Please guide me what to do.

I've already used FileShare.ReadWrite attribute and File.OpenRead(path) with my code but it doesn't work for me.

Sherantha
  • 462
  • 3
  • 19

2 Answers2

0

Your problem is that File.Create will open a stream allowing you to do what you like to the file refer : http://msdn.microsoft.com/en-us/library/d62kzs03.aspx

Therefore, technically, it is in use already.

Just remove the File.Create altogether. The StreamWriter will handle creating the file if it doesn't exist.

When using streams it is good practice to do

using (Stream s = new Stream())
{
} // Stream closes here
If you also create the output stream, make sure to close it.

refer http://www.codeproject.com/Questions/1097511/Can-not-opening-pdfs-generated-using-pd-ml-using-C

S M
  • 3,133
  • 5
  • 30
  • 59
0

You're leaking a stream object that you should be disposing. Specifically, the one passed as the second parameter here:

pd4ml.render(stream,new System.IO.FileStream(FileName, System.IO.FileMode.CreateNew));

Rather than creating the new stream as part of that method call, you should place it in another variable and Dispose it (preferably making use of using statements for it and for stream, rather than manually).

using(var stream2 = new System.IO.FileStream(FileName, System.IO.FileMode.CreateNew))
{
  pd4ml.render(stream,stream2);
}
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448