I am trying to combine a few Word docs and create one final doc using VB.NET as a part of a Windows application. But the Word document object is getting disconnected from RPC while trying to edit the final resulting document.
I am trying to copy content of one doc (just for example) and pasting it in the newly created doc
Desired Behaviour: The code will read a Word document, and copy its contents, and paste it into a new Word document.
Here is a code sample showing what I am trying to do,
Dim wordApp As Word.Application = Nothing
wordApp = New Word.Application
'Create a new final document
Dim finalDocument As Word.Document = Nothing
Try
'Create a new final document
finalDocument = wordApp.Documents.Add()
'Adding Initial template doc
Dim doc_Template_File As
Word.Document=wordApp.Documents.Open(doc_Template_FilePath)
'Do some editing
'Copy the content from one file
doc_Template_File.Content.Copy()
If finalDocument IsNot Nothing Then
finalDocument.Range.Paste() 'Getting the exception at this line
finalDocument.Range.InsertParagraphAfter()
doc_Template_File.Close(SaveChanges:=False)
End If
Catch ex As Exception
'Handle exception
Finally
' Release resources
If finalDocument IsNot Nothing Then
finalDocument.Close()
If wordApp IsNot Nothing Then
wordApp.Quit()
helper.ReleaseComObject(wordApp)
End If
End Try
I have tried to create the wordApp object in different ways too, as it was mentioned in some posts
Dim wordApp As Word.Application = Nothing
wordApp = New Word.Application
and
wordApp = Marshal.GetActiveObject("Word.Application")
On debugging I have observed that the object creation, opening the doc_Template_FilePath is successful. But exception is rising when I am trying to paste the content into the new doc (as mentioned in the code above) at finalDocument.Range.Paste() 'Getting the exception at this line
. Here is the exception detail,
Source:: Microsoft.Office.Interop.Word Source:: System.Runtime.InteropServices.COMException (0x80010108): The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED))`
Any suggestion or clues on how to resolve this? What am I missing here?