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:
- 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";
- Call the ShowDialog method to display the SaveFileDialog dialog box.
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// 用户点击保存按钮
// 可以通过saveFileDialog1.FileName获取用户选择的文件路径
}
- 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.