Use Open XML to read already open Word documents?
All examples and implementations I've seen use some type of code, for example:
//filePath is some path to a docx file
using (WordprocessingDocument wpd = WordprocessingDocument.Open(filePath, true))
{
//Do stuff here
}
which requires your file to be closed. I want to be able to use the Open XML SDK operations on an already open document, because I want to do something while the user is actively viewing the document, and I won't necessarily save it.
Is it possible? My understanding is that Word is probably blocking the document if it is open, so you cannot open the file (even for Read-Only). Is there a way to get around this?
It would be really nice if I could somehow use the Open XML SDK on already open documents. One of my ideas is to temporarily save an already open file and run the OpenXML stuff in a temporary file and somehow reconcile it with an existing document using the Office API. Haven't thought about it, but this is not the ideal way I would like to do it.
I also know of a Word API property that returns an XML string by doing Word.Range.XML
. However, I am not sure how to load this string value into the SDK so that I can use its methods to help me.
source to share
The Word add-in along with the Open Xml SDK seems to suit your requirements. You can find a sample @ http://blogs.msdn.com/b/atverma/archive/2012/01/11/utility-to-generate-word-documents-from-templates-using-visual-studio-2010-and -open-xml-2-0-sdk-part-3.aspx
source to share
You can open an Open XML SDK text document with a file already open by office. You must first open a FileStream and then open the Word document that defines that stream. Here's an example:
using (Stream stream = new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite))
{
using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, false))
{
....
}
}
source to share