I could see a lot of very similar threads all around, but nothing seem to give me a solution which ought to be very basic.
From my winforms application, I need to close a running instance of a word document (opened from the application itself). When I open the word document from the application, I keep a track of it in a list. Now how can I close the same doc?
Here is what I tried:
private bool CloseWord(string osPath) //here I pass the fully qualified path of the file
{
try
{
Word.Application app = (Word.Application)Marshal.GetActiveObject("Word.Application");
if (app == null)
return true;
foreach (Word.Document d in app.Documents)
{
if (d.FullName.ToLower() == osPath.ToLower())
{
d.What? //How to close here?
return true;
}
}
return true;
}
catch
{
return true;
}
}
I get a lot of methods for the document object, but only a .Close()
to close which has arguments like this: ref object SaveChanges, ref object OriginalFormat, ref object RouteDocument
which I dont understand.
What is the ideal way? Thanks..
Edit:
I can not close the entire Word application (WinWord) as users might have other word files opened.
I need to just terminate the word instance (something like
Process.Kill()
) without any prompt for user to save or not etc.
If you want to close whole word application, you can just call:
I know it is too late, but I found this topic because I had the same problem.
And my solution may help other people.
The solution above didnt work well because it killed every running instance of Word, though it wasn't opened by the c# program but the user.
So this was not that userfriendly.
My code checks the processes before/after the creation of the
Word.Application
Object in c# and writes the IDs of theWINWORD
Processes inList<int>
then it compares the values in bothList<int>
. When aprocessID
is not found in bothList<int>
it kills the process with this ID.Run this twice (one time before the creation of the Word.Application and once after).
Then run
killProcesses(processesbeforegen, processesaftergen);
This solution got from here solves.
How about using something like:
Modified From: http://www.dreamincode.net/code/snippet1541.htm