Microsoft 365
Formerly Office 365, is a line of subscription services offered by Microsoft which adds to and includes the Microsoft Office product line.
5,097 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have a C# program that uses Microsoft.Office.Interop.Word.dll (15.0.0.0) to repeatedly open Word files, gather information, and close them. However, while my application is running in the background, if I try to manually open a Word file from Explorer or another method, the file opens briefly but then closes unexpectedly.
Does anyone have a solution for this issue?
Conditions:
If the Word file is opened manually before the C# application starts, the manually opened file is not closed, as it seems to be attached to the first Word process that was already running.
Sample source
public override IEnumerable<LinkInfo> GetLinkInfo(string filePath)
{
Application application = null;
Document document = null;
try
{
try
{
application = new Application
{
Visible = false,
DisplayAlerts = WdAlertLevel.wdAlertsNone,
AutomationSecurity = MsoAutomationSecurity.msoAutomationSecurityForceDisable
};
document = application.Documents.Open(
FileName: filePath,
ReadOnly: true,
PasswordDocument:"DummyPassword",
PasswordTemplate: "DummyPassword");
}
catch (Exception ex)
{
throw ex;
}
foreach (Hyperlink hyperlink in document.Hyperlinks)
{
if (string.IsNullOrEmpty(hyperlink.Address))
{
continue;
}
string text = string.Empty;
Range range = null;
if (hyperlink.Type == MsoHyperlinkType.msoHyperlinkRange)
{
text = hyperlink.TextToDisplay;
range = hyperlink.Range;
}
else
{
text = SHAPE_TEXT;
range = hyperlink.Shape.Anchor;
}
int pageNumber = range.Information[WdInformation.wdActiveEndPageNumber];
yield return new LinkInfo(hyperlink.Address, text, "P." + pageNumber.ToString());
}
}
finally
{
document?.Close(false);
application?.Quit();
if (document != null)
{
Marshal.ReleaseComObject(document);
}
if (application != null)
{
Marshal.ReleaseComObject(application);
}
}
}