Hello @Pieter Claassens ,
I'm glad you were able to resolve the issue. For anyone who might encounter a similar problem in the future, I'd like to provide some additional context.
There are typically three common scenarios when opening Word documents:
- Simply viewing the document - letting the user open and interact with it normally
- Reading or modifying content programmatically - extracting or changing text, tables, etc. without showing the UI
- Automating Word with full UI access - using Word's specific features like macros, formatting tools, or displaying the application to users
Since you're using Office Interop to open Word with visible UI, you've chosen option 3. However, there are some important considerations to keep in mind:
- Every machine running your application must have Microsoft Office installed.
- Microsoft explicitly doesn't support Office automation in server-side applications (ASP.NET, Windows Services, Azure Functions, etc.) due to security, stability, and performance concerns.
- Without proper cleanup, Word processes can remain running in the background, causing memory leaks.
You could use this code snippet as a reference:
using Microsoft.Office.Interop.Word;
using System;
using System.Runtime.InteropServices;
Microsoft.Office.Interop.Word.Application wordApp = null;
Document doc = null;
try
{
wordApp = new Microsoft.Office.Interop.Word.Application();
object filePath = @"C:\Test\NewDocument.docx";
object readOnly = false;
object isVisible = true;
object missing = Type.Missing;
doc = wordApp.Documents.Open(ref filePath, ref missing, ref readOnly,
ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing,
ref missing, ref isVisible);
wordApp.Visible = true;
// Your work with the document here
}
catch (Exception ex)
{
MessageBox.Show($"Error opening document: {ex.Message}");
}
finally
{
// Cleanup COM objects
if (doc != null)
{
doc.Close(false);
Marshal.ReleaseComObject(doc);
}
if (wordApp != null)
{
wordApp.Quit(false);
Marshal.ReleaseComObject(wordApp);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}