3

I need to be able to change the name of the default document from Document1 to Report when a Word document is started from my application. The problem is that the name property in the Document object is read only. Any idea on a method I can call at startup that changes the name?

Blade3
  • 4,140
  • 13
  • 41
  • 57
  • Interesting.. I went a verified this myself. I guess it's akin to creating a new document within the GUI, and it having a default name (Document1, Document2, ... etc) before you save it. I'd guess that the best way around this then is to save the document first programmatically, then open it. – B L Jan 17 '13 at 15:44

1 Answers1

2

You might be interested in this snippet of code:

    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

    object missing = System.Reflection.Missing.Value;
    object fileName = "Report";
    object isReadOnly = false;
    object isVisible = true;

    Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref isVisible);

    doc.SaveAs2(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref isReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);          
    wordApp.Visible = true;

This will pop open a new Word document named "Report" as you specified. Notice this uses the concept I mentioned in the comment, that is, it saves the file first with a new name then opens it. In this case, the default location is probably your User's "Documents" folder, but you can specify the path as needed.

Don't forget to close and release the COM objects "doc" and "wordApp" as needed. Sometimes the GC doesn't mop it all up appropriately, especially if the application closes unexpectedly or if you forget to close any of them when you're done.

B L
  • 1,572
  • 1
  • 14
  • 26