Search code examples
c#.netms-wordoffice-interopfilesystemwatcher

Converting doc to pdf using Interop.Word C#


I'm using C# to convert the .doc to .pdf. The .doc is on the vendor's site. To get the .doc, we have to click on a button which presents us with option to Open, Save, or Cancel. When the user clicks on Save button, it prompts for the location. The user chooses the location in mapped drive, say, S:\Some Folder\abc.doc, and the actual folder location is \\server\\folder\Some Folder. This is where my program comes in to play. I'm using FileSystemWatcher class in c# with Filter set for .doc files. I can see in debug that the file is found. The folder location is hardcoded and saved as the actual folder location mentioned above. The user and the application has full permission to the folder. However, I'm getting FileNotFoundException when I run the program.

This is what I have

        WriteToFile("Starting Word application");
        Application word = new Application();

        object missing = Type.Missing;

        var sourcefile = new FileInfo(path);

        // check if the created file ends with .doc. 
        System.Diagnostics.Debug.WriteLine(path);
        if (!path.ToLower().EndsWith(".doc"))
        {
            return "";
        }

        word.Visible = false;

        WriteToFile("Opening doc as read only");
        // open readonly            
        System.Diagnostics.Debug.WriteLine(sourcefile.FullName);
        var doc = word.Documents.Open(FileName: sourcefile.FullName, ReadOnly: true);

The strange thing is sourcefile.FullName doesn't show the hard coded server address that path is set to. It shows the file path as S:\Some Folder\abc.doc, which makes no sense to me. What's going on here, and why can't it find the file?


Solution

  • The OnCreate event can fire when the underlying file is still in use/being written to which can cause problems if you immediately try to access it.

    The simple solution is to introduce either an arbitrary delay to allow for the file to be closed by the process creating it, or better a loop with a short delay that attempts to access the file, catches the relevant exception should it occur and retries.