Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c# 2.0 - how to close a running instance of Word document? (C#)

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:

  1. I can not close the entire Word application (WinWord) as users might have other word files opened.

  2. I need to just terminate the word instance (something like Process.Kill()) without any prompt for user to save or not etc.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...