How is the SaveFileDialog used in C#?

SaveFileDialog class is used to display a dialog box that allows the user to choose the location and name of the file to be saved. Here are some common uses of SaveFileDialog:

  1. Create a SaveFileDialog object and adjust its properties:
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.Title = "Save File";
saveFileDialog1.InitialDirectory = @"C:\";
saveFileDialog1.FileName = "myfile.txt";
  1. Call the ShowDialog method to display the SaveFileDialog dialog box.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    // 用户点击保存按钮
    // 可以通过saveFileDialog1.FileName获取用户选择的文件路径
  1. Save operation using the file path selected by the user.
using (StreamWriter sw = File.CreateText(saveFileDialog1.FileName))
    sw.WriteLine("Hello, World!");

By following the above steps, you can use the SaveFileDialog class in C# to allow users to select the location and file name for saving a file, and save the file to the specified location.

Leave a Reply 0

Your email address will not be published. Required fields are marked *