Reputation: 1113
I creating VSTO Add-In that will send documents to server via REST API.
I need send currently opened document (e.g. docx
) just as a file.
First problem was getting full name of the active document. If found the only way:
Path.Combine(Globals.ThisAddIn.Application.ActiveDocument.Path,
Globals.ThisAddIn.Application.ActiveDocument.Name)
This code can return good path on local drive: D:\Docs\Doc1.docx
But also it can return HTTP path to document in a cloud (e.g. OneDrive
): https://d.docs.live.net/xxxxx/Docs\Doc1.docx
Even if it would only local documents I can't get file of this document. I tryed this code:
using (var stream = new StreamReader(docFullPath)) { }
And in case of locally stored document I got System.IO.IOException: The process cannot access the file because it is being used by another process
. Not surprizing.
And in case of cloud stored document I got System.NotSupportedException: The given path's format is not supported
. Of cource!
I believe I'm doing all wrong and my goal is reachable. My question is: How read file of currently opened document on MS Office App from Add-In without closing App?
Upvotes: 2
Views: 2430
Reputation: 176159
Even if you could access the file ActiveDocument.FullName
points to there is no guarantee that the user already has saved all changes to disk, or even worse, the document is still in the state of creation and has never been saved yet.
There is another little known/documented way to retrieve a file of an open document which is using the IPersistFile
COM interface which is implemented by the Document
object. The following sample saves a document to the specified location. This happens without modifying the save state of the document, i.e. you get the exact version of the document as it is open (and not as it has previously been saved to disk) and the user may later still decide to save possible modifications of the document or not.
public static void SaveCopyAs(this Document doc, string path)
{
var persistFile = (System.Runtime.InteropServices.ComTypes.IPersistFile)doc;
persistFile.Save(path, false);
}
Upvotes: 4
Reputation: 3519
You can copy an open document on the filesystem using File.Copy(FullName, <some_temp_filename>)
, and then send the copy to your REST service. This works even though it's still open for exclusive reading/writing in Word.
Upvotes: 0