0

when I try to open my pdf report from my program, if the pdf file is already open it shows exception like "The process cannot access the file 'path..\sample.pdf' because it is being used by another process".. how can I show a message that the document is open. or how can I reopen the same opened pdf file according to my request?? It shows exception on this line

PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"F:\\reports\\" + "DepartmentPresentReport.pdf", FileMode.Create));
Semil Sebastian
  • 111
  • 1
  • 5
  • 18

3 Answers3

1

try using a try/catch to handle the exception

try
{
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"F:\\reports\\" + "DepartmentPresentReport.pdf", FileMode.Create));
}
catch (Exception e)
{
    // close already open file/ return exception
}
user2835725
  • 154
  • 6
1

You can even catch the exception using FileStream

private bool IsFileInUse(string path, FileAccess access = FileAccess.Write)
    {
        try
        {
            using (var fs = new FileStream(path, FileMode.Open, access, FileShare.Read)) { }
        }
        catch (IOException e)
        {
            return (Marshal.GetHRForException(e) & 0xFFFF) == 32;
        }
        return false;
    }
Rohit Prakash
  • 1,975
  • 1
  • 14
  • 24
0

The first simple solution is that you can use try catch statement to open the file and handle the error based on the error message (ID)

Rajesh
  • 1,600
  • 5
  • 33
  • 59
Hamid Jolany
  • 800
  • 7
  • 11