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.
This solution got from here solves.
Word.Application app = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
if (app == null)
return true;
foreach (Word.Document d in app.Documents)
{
if (d.FullName.ToLower() == osPath.ToLower())
{
object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;
object routeDocument = false;
d.Close(ref saveOption, ref originalFormat, ref routeDocument);
return true;
}
}
return true;