In C#, SaveFileDialog
the control is used to create a save file dialog box, allowing the user to specify the path and file name of the saved file. SaveFileDialog
Provides an easy way for the user to choose a path and filename to save the file, and get the path of the file selected by the user. The following is SaveFileDialog
the detailed usage of the control:
-
Create and display the save file dialog:
- Create a
SaveFileDialog
object instance:SaveFileDialog saveFileDialog1 = new SaveFileDialog();
- Set dialog properties such as default folders, file type filters, etc.
- Call
saveFileDialog1.ShowDialog()
the method to display the save file dialog.
- Create a
-
Handle user's file saving:
- After the user selects the file saving path and file name,
SaveFileDialog
the object'sFileName
property will contain the path of the file selected by the user. - Use
saveFileDialog1.FileName
the attribute to get the user-specified file path.
- After the user selects the file saving path and file name,
Here is an example showing how to use SaveFileDialog
the control:
using System;
using System.Windows.Forms;
namespace SaveFileDialogExample
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 创建保存文件对话框
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
// 设置对话框的属性
saveFileDialog1.InitialDirectory = "C:\\"; // 设置默认文件夹
saveFileDialog1.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*"; // 设置文件类型过滤器
// 显示保存文件对话框
DialogResult result = saveFileDialog1.ShowDialog();
// 处理用户的文件保存
if (result == DialogResult.OK)
{
// 获取用户所选文件的路径
string selectedFilePath = saveFileDialog1.FileName;
// 在 label1 中显示保存的文件路径
label1.Text = "保存的文件路径为:" + selectedFilePath;
}
}
}
}
In the above example, we created a form application called "MainForm" and placed a button and a label on the form. In the button's click event, we create a SaveFileDialog
object saveFileDialog1
and set properties of the dialog, such as the default folder and file type filters. Then, we call saveFileDialog1.ShowDialog()
the method to display the save file dialog. After the user selects the path and file name to save the file, we saveFileDialog1.FileName
get the file path specified by the user through the attribute, and display the path in the label.
Hope this example can help you understand and use SaveFileDialog
the detailed method of the control. If you have any further questions, please feel free to ask!