I have some C# code that I want to apply to a single open Word document using Interop. Below's my attempt.
Microsoft.Office.Interop.Word.Application application =
(Microsoft.Office.Interop.Word.Application)
System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
if( application != null && application.Documents.Count > 0)
{
Document document = application.ActiveDocument;
}
application is non-null but application.Documents.Count is equal to zero even though I have a Word document open? If I remove the test for application.Documents.Count > 0 and then this line
Document document = application.ActiveDocument;
throws the error
System.Runtime.InteropServics.COMException: 'This command is not
available because no document is open.'
Is there something additional I need to do for application to recognize my open Word doc?
Related
This dead-simple code creates a file that Excel won't open.
How could this be failing?
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(#"c:\dir\src.xlsx", true))
{
doc.SaveAs(#"c:\dir\saved.xlsx");
}
Notes:
Excel won't open saved.xlsx
src.xlsx is known to exist and be valid (Excel opens it no problem)
saved.xlsx is indeed produced, though it's about 500 bytes smaller than src.xlsx
If you meant this error:
Stop debugging before opening the "saved.xlsx" file
I've checked. It works correctly:
Output file
The code below is supposed to open a .docx file in my windows directory but instead of opening the file it opens only the Word Application. There is no active word document inside, not even a new document. I notice that under the file tab options like "save, save as, print, Share, Export, and Close" are all grayed out and inactive.
using Microsoft.Office;
using Word = Microsoft.Office.Interop.Word;
class Program
{
static void openFile()
{
string myText = #"C:\CSharp\WordDocs\MyDoc.docx";
var wordApp = new Word.Application();
wordApp.Visible = true;
wordApp.Activate();
Word.Documents book = wordApp.Documents;
Word.Document docOpens = book.Open(myText);
}
static void Main(string[] args)
{
//Console.WriteLine("Hello World\n");
openFile();
}
}
Running your code but with a path that doesn't exist does indeed opens Word Application with no document inside. But it does throw a very informative exception as follows:
System.Runtime.InteropServices.COMException: 'Sorry, we couldn't find
your file. Was it moved, renamed, or deleted?
(C:\Users\nonexistantuser...\Test.docx)'
You failed to mention this in your question, but you must get an exception.
So my guess is your path is incorrect.
If the path is correct, i.e. the file exists, another possible scenario is not having appropriate read permissions. In that case again it would open an empty Word Application, but that too should throw an exception albeit a different one:
System.Runtime.InteropServices.COMException: 'Word cannot open the document: user does not have access privileges
(C:\Users\NS799\Desktop\Test.docx)'
So please check if the path exists and if it does, if you have appropriate permissions.
try
{
Microsoft.Office.Interop.Word.Application WordObj = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application") as Microsoft.Office.Interop.Word.Application;
Office.CustomXMLParts currClassification = WordObj.ActiveDocument.CustomXMLParts;
}
catch(Exception ex)
{
//I am getting, This command is not available because no document is open. this error here.
}
When I am using above code, I am getting this error:
This command is not available because no document is open.
Regards
Actually you are trying to access active document when there is no document open in word application so you are getting an error.
Your word application is open but no document is opened in it i.e. you are at home screen of word application as shown in image.
Try to use following code to check whether there are any open documents in your application and then access ActiveDocument
if(WordObj.Documents.Count >= 1)
have a word document and I want to get word count programmatically using OpenXML sdk,
I managed to get word count but openXML returns wrong values.
note that the test document is mixed languages (Arabic, English) Arabic is RTL language.
if you open the word document using Microsoft word in the UI it gives you the correct number of words
but if you go and get the value stored in the app.xml file for the same document you will get different value.
I tried the code in this link
https://msdn.microsoft.com/en-us/library/office/bb521237(v=office.14).aspx
// To retrieve the properties of a document part.
public static void GetPropertyFromDocument(string document)
{
XmlDocument xmlProperties = new XmlDocument();
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open(document, false))
{
ExtendedFilePropertiesPart appPart = wordDoc.ExtendedFilePropertiesPart;
xmlProperties.Load(appPart.GetStream());
}
XmlNodeList chars = xmlProperties.GetElementsByTagName("Characters");
MessageBox.Show("Number of characters in the file = " +
chars.Item(0).InnerText, "Character Count");
}
the file I tested contains
word count is 13 but using upper code it gives me 11!
DocIO is a .NET library that can read, write and render Word 2003/2007/2010/2013/2016 files. Using DocIO library of Syncfusion, you can get the correct word count. The whole suite of controls is available for free (commercial applications also) through the community license program if you qualify. The community license is the full product with no limitations or watermarks.
Step 1: Create a console application
Step 2: Add reference to Syncfusion.DocIO.Base, Syncfusion.Compression.Base and Syncfusion.OfficeChart.Base; You can add these reference to your project using NuGet also.
Step 3: Copy & paste the following code snippet.
This code snippet will produce the words count in the Word document as per your requirement.
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using System.IO;
namespace DocIO_MergeDocument
{
class Program
{
static void Main(string[] args)
{
//Creates a new Word document
WordDocument document = new WordDocument(#"InputDocument.docx");
//Update the words count in the document.
document.UpdateWordCount(false);
//Get the updated words count
int wordCount = document.BuiltinDocumentProperties.WordCount;
//Releases the resources occupied by WordDocument instance
document.Dispose();
}
}
}
For further information about DocIO, please refer our help documentation
Note: I work for Syncfusion
I am converting a large number of MS Word documents to PDFs using the Interop library in a multi-threaded WPF application (.NET Framework 4). I get the following error on some word documents:
It blocks the current thread until I click OK on the dialog and then continues with the conversion and the converted PDF comes out to be fine as well.
This only happens on certain documents. I am running the application on multiple computers and this has occured on other computers too.
Below is my code for conversion:
var wordApplication = new Microsoft.Office.Interop.Word.Application();
// Opening the word document
var wordDocument = wordApplication.Documents.Open(tempFile, false, true, false, NoEncodingDialog: false);
// Exporting the document to the PDF
wordDocument.ExportAsFixedFormat(pdfPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
// Closing the document and the application.
((Microsoft.Office.Interop.Word._Document)wordDocument).Close(false);
((Microsoft.Office.Interop.Word._Application)wordApplication).Quit(false);
Marshal.ReleaseComObject(wordDocument);
Marshal.ReleaseComObject(wordApplication);
wordDocument = null;
wordApplication = null;
Does anyone know what could be causing this? Or whether I can close this dialog box from my application?
Thanks
wordApplication.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
This seem to have fixed the issue.
Thanks bibadia for providing the link to the question that had the fix.