Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

c# word gen document and save window dialog

  1. User

    c# word gen document and save window dialog

  2. Assistant

    To create a Word document in C# and save it using a SaveFileDialog window dialog, you can use the following code:

    using Microsoft.Office.Interop.Word;
    using System.Windows.Forms;
    
    // create a new Word application and document
    var wordApp = new Application();
    var wordDoc = wordApp.Documents.Add();
    
    // insert some text into the document
    wordDoc.Content.Text = "Hello, World!";
    
    // open a file save dialog to choose a filename and location to save the document
    var saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "Word Document (*.docx)|*.docx";
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // save the document to the selected location
        wordDoc.SaveAs2(saveFileDialog.FileName);
    }
    
    // close the document and quit the application
    wordDoc.Close();
    wordApp.Quit();
    

    In this code, we first create a new Word application and document, and then add some text to the document. We then create a SaveFileDialog object and set its filter to only allow saving Word documents with a .docx extension.

    Next, we show the file save dialog by calling its ShowDialog() method. If the user selects a file name and clicks the "Save" button, we get the selected filename from the FileName property of the SaveFileDialog object, and then save the Word document to that location using the SaveAs2() method of the Document object.

    Finally, we close the Word document and quit the Word application. Note that you should always make sure to close the document and quit the application when you are done with them, to avoid memory leaks.