2

How do you create a clone of a word document in c#? (office 2007 libraries)

public copyDocument (Word.Document _originalDocument)
{
    //How do I clone the _originalDocument?
    Word.Document clonedDocument = _originalDocument;

    //Do stuff to cloneDocument without effecting _originalDocument
}

So what I want to do is grab a clone of the original document and then make changes to it without effecting the original document. With the above, if I make changes to cloneDocument they will also be applied to _originalDocument.

Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
user1255276
  • 541
  • 2
  • 5
  • 20
  • Have you tried saving a copy of it in the new location and then opening that new copy? – George Johnston Apr 29 '13 at 19:12
  • Does your code run inside an interactive instance of Word (i.e. as an add-in) where the document in question is also edited by the user? Or is your application stand-alone (running in the background)? – Dirk Vollmar Apr 30 '13 at 10:57
  • George - Thx but that isn't an option I'm afraid :/ has to be saved in memory. – user1255276 Apr 30 '13 at 16:47
  • 0xA3 - Yes it's as an add-in and the document can continue to be edited by the user. - The Original is the current open document that is running and the clone is copy of the document made on an event. Which I would want to swap back in at a later time. – user1255276 Apr 30 '13 at 16:47

1 Answers1

0

Since you are using office 2007 it might be well worth your time to check out DocX

DocX allows you to load or create a document in memory without having to open Word behind the scenes (Office 2007 supports an XML-like format). It's fast and lightweight and it doesn't even require to have Word installed (really convenient if you are deploying on a server).

Also, you can easily clone a document, make changes to the clone and save it and it won't affect the original:

DocX testTemplate = DocX.Load("C:\\test.docx");
Paragraph p = testTemplate.InsertParagraph("Hello World.");

DocX testDoc = testTemplate;
Paragraph p = testDoc.InsertParagraph("Foo.");

testDoc.SaveAs("C:\\test2.docx");
testTemplate.Save();

//testTemplate only contains a "Hello World" paragraph
Nick Patsaris
  • 2,118
  • 1
  • 16
  • 18
  • Thx for the suggestion Circular Reference but I can't use 3rd party lib's :( – user1255276 May 01 '13 at 13:33
  • hm... I played around with it but couldn't reproduce your error, the original document was not affected. If you're still looking for an answer, can you share more source-code? – Nick Patsaris May 04 '13 at 22:58