1
votes

I have code that writes text to a Word document (non-XML) and saves it to a file. Now, I'm trying to modify it so that the document is created and the user is then prompted to save the document.

This is the code for creating the Word document:

object miss = System.Reflection.Missing.Value;
object Visible = true;
object start1 = 0;
object end1 = 0;
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
Document aDocument = WordApp.Documents.Add(ref miss, ref miss, ref miss, ref miss);
Range rng = aDocument.Range(ref start1, ref miss);

try
{
    rng.Font.Name = "Georgia";
    rng.InsertAfter("Report Header!");
    object filename = @"C:\Users\test.doc";

    aDocument.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
    object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdPromptToSaveChanges;
    object originalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdWordDocument;
    object routeDocument = true;
    ((_Document)aDocument).Close(saveChanges, originalFormat, routeDocument); //to close the document process (winword.exe)
    //WordApp.Visible = true;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}        

This works as expected; it creates a Word document and opens it for the user. I've been reading this link from Microsoft about saving files using the SaveFileDialog, but I'm not entirely sure how to apply it to my situation. Since the SaveFileDialog provides a stream object to write to, should I read from the Word file and write it to the stream? If that's the case, I'm not sure how to code it, but that seems like a roundabout way. Is there a way to pass the created Word document directly to the SaveFileDialog?

1

1 Answers

5
votes

The SaveFileDialog could be used simply to give, to your user, an interface to select a folder and a name. Then it's up to you to save the file.

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Word document|*.doc";
saveFileDialog1.Title = "Save the Word Document";
if(DialogResult.OK == saveFileDialog1.ShowDialog())
{
    string docName = saveFileDialog1.FileName;
    if(docName.Length > 0)
    {
        object oDocName = (object)docName;
        aDocument.SaveAs(ref oDocName, ref miss, ref miss, ref miss, ref miss, ref miss,  
                     ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, 
                     ref miss, ref miss, ref miss, ref miss); 
        WordApp.Visible = true; 
    }
}

The method you mention in your question is documented by MSDN in this article, but in your case is more practical to let the MSWORD application do the saving operation on its file.