4
votes

All examples and implementations I've seen employ some type of code like:

//filePath is some path to a docx file
using (WordprocessingDocument wpd = WordprocessingDocument.Open(filePath, true))
{
    //Do stuff here
}

which requires your file be closed. I want to be able to use the Open XML SDK operations on an already open document because I'll want to do stuff while the user is actively looking through the document, and I won't necessarily want to save it.

Is this possible? I realize Word probably locks the document if it is open, so you are unable to open the file (even for Read-Only). Is there any way around it?

It'd be really nice if I could somehow use the Open XML SDK on already open documents. One idea I've had is saving the already open file temporarily, and running the OpenXML stuff on temp file and somehow reconcile that with the existing doc using the Office API. Haven't thought this approach through, but it's not the ideal way I'd want to do it.

I also know of a property on the Word API that returns an XML string by doing Word.Range.XML. However, I'm unsure how to load this string value to the SDK so I can leverage its methods to help me.

2
When a file is open read-only, it's open read-only, and Word (and most other Office apps) do indeed open files in that mode. AFAIK, it's not possible to tell the OS that read-only should be ignored once it's in effect. (And that's actually good - can you imagine the possible effects of being able to say "Gee, ignore the fact someone said they want to lock the file to allow others read-only access, and give me access anyway."?) - Ken White
Yeah, I fully understand why it is locked. I guess I had some notion that because we could manipulate the file through the Word API, I could do the same with Open XML, but that was wrong. - Shark

2 Answers

11
votes

You can open word document Open XML SDK with file already open by office. You should open a FileStream at first and then open word document specifying this stream. Here is an example:

using (Stream stream = new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
 using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, false))
 {
  ....
 }
}