Reputation: 19
I have this codes:
Process MSWprocess = new Process();
if (CommandToMSWord[1][1] == "Edit")
{
MSWprocess = Process.Start(PatientLetterDocx);
}
MSWprocess.WaitForExit();
if (CommandToMSWord[2][1].ToUpper() == "FALSE" && MSWprocess.HasExited)
{
File.Delete(PatientLetterDocx);
}
Wherein MSWprocess
would be opening a MS Word document and if the user wants to automatically save this on exit, CommandToMSWord[2][1].ToUpper()
should be TRUE, else the document would be deleted upon closing the MS Word document.
When I execute the program for the first time, it waits until the MS Word is closed. When I execute another instance of the same program while the first instance is still running(still waiting for the MS word to be closed), the second instance doesn't care about the WaitForExit()
any more and causes a run time error because the program is deleting a file which is still open.
How I like it to be is that even if the program is running multiple times simultaneously, the WaitForExit()
should really do its part every time.
Do you have any ideas why this is not working for multiple instances simultaneously?
Thanks in Advance.
Upvotes: 1
Views: 283
Reputation: 3161
This is because of how Word works. When Word process is running and you lunch another process, information is passed to first one and second process exits. The document is really opened by the first process. You can use command line switches to make word run separate process for your files. If I remember right it is /t
although I do not have currently Word installed so I can not check this.
Upvotes: 1
Reputation: 13085
You should declare MSWprocess
as a local variable instead. As you don't each time this snippet is run, it will overwrite the instance variable. Try this instead.
var MSWprocess = Process.Start(PatientLetterDocx);
Upvotes: 0