1
votes
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.

2
try using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))Marcus Höglund
why don't you close it first?DDave
but to close it I've to open it first and when I tried to open it it gives me exception. And I've used FileShare.ReadWrite but it doesn't work for me.Khanjan Bhatt
Are you creating a new file??S M
Yes I'm creating a new file using pd4ml.render(stream, new System.IO.FileStream(FileName, System.IO.FileMode.CreateNew)). And after this creation file is opened somewhere in system internally that I can't detect.Khanjan Bhatt

2 Answers

0
votes

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

0
votes

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);
}