c# word gen document and save window dialog
- User
c# word gen document and save window dialog
- 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
SaveFileDialogobject and set its filter to only allow saving Word documents with a.docxextension.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 theFileNameproperty of theSaveFileDialogobject, and then save the Word document to that location using theSaveAs2()method of theDocumentobject.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.