简体   繁体   中英

Error when trying to close an active Word document in c# application

I'm using c# with .net 4.0 Framework and Office 2010

I'm currently trying to figure out how to close an already open word document. I'm running into an error with this code:

Microsoft.Office.Interop.Word.Application app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
        foreach (Microsoft.Office.Interop.Word.Document d in app.Documents)
        {
            if (d.FullName.ToLower() == "OOPOR".ToLower())
            {
                object saveOption = WdSaveOptions.wdPromptToSaveChanges;
                object originalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
                object routeDocument = false;
                d.Application.Documents.Close(ref saveOption, ref originalFormat, ref routeDocument);

            }
        }

Currently, when I run this code, I cannot get into the foreach loop. the app.Documents shows a count of '0'. and if I set a break point at the foreach loop and look at the 'app' variable, it states:

ActiveDocument = '((Microsoft.Office.Interop.Word.ApplicationClass)(app)).ActiveDocument' threw an exception of type 'System.Runtime.InteropServices.COMException' >> 
base {System.Runtime.InteropServices.ExternalException} = {"This command is not available because no document is open."}

This occurs even though I have an active word document.

It seems my issue was stemming from a user vs admin conflict.

My application running with elevated privileges was unable to see the Word.Application and its documents running as a standard user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM