简体   繁体   中英

C# save word document without prompt give 'document is opened elsewhere error'

I have a windows form with Office Word inside it. I am opening word documents programmatically with code (_wd is of type Microsoft.Office.Interop.Word.ApplicationClass - I am using VS 2012, .NET 4.5, Office 2007):

  public void LoadComponent(string path) { if (_wd.Documents.Count != 0) _wd.ActiveDocument.Close(); _wd.Documents.Add(ref path); } 

My problem comes when I want to save active document. I don't want save prompt to appear - here's what I've tried, and couldn't cancel the prompt dialog:

_wd.ActiveDocument.Saved = true;
_wd.ActiveDocument.Save();

If I try with:

_wd.ActiveDocument.SaveAs(_filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

I receive Exception: 'Word cannot save this file because it is already open elsewhere.' - but it is opened only inside my application, nowhere else. How to save Word document which is opened without save prompt dialog programmatically? Interesting thing is that even if I try to save the document by pressing 'save' button I got save prompt dialog -> like the document was not created before on disc. But, the document is opened from disc, only it is opened programmatically. If I open the document with Word and then press 'save' I never got save prompt dialog.

I receive Exception: 'Word cannot save this file because it is already open elsewhere.'

You should only receive this when your document is open in another instance of Application .

The following example works for me, and does not prompt:

var path = @"C:\Temp\temp.docx";

Word.Application wordApp = new Word.Application();
Word.Documents documents = wordApp.Documents;
Word.Document doc = documents.Add(path);
doc.Range().Text = "Test Text";
doc.SaveAs2(path);
wordApp.Quit();

Check for stray instances of the WINWORD.EXE process in your task manager. They can occur if an instance of Application is not properly close(programmatically).

One of these stray processes may be holding your Document open.

Seems that you are not the only one expiriencing it. May be a bug in MSWORD . As suggested here

·         Click on start->run.
·         Type %appdata% and click ok.
·         Go to Microsoft->templates folder and delete Normal.dotm.
·         Restart word

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