Detailed usage of saveFileDialog1 control in C#

In C#, SaveFileDialogthe control is used to create a save file dialog box, allowing the user to specify the path and file name of the saved file. SaveFileDialogProvides 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 SaveFileDialogthe detailed usage of the control:

  1. Create and display the save file dialog:

    • Create a SaveFileDialogobject 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.
  2. Handle user's file saving:

    • After the user selects the file saving path and file name, SaveFileDialogthe object's FileNameproperty will contain the path of the file selected by the user.
    • Use saveFileDialog1.FileNamethe attribute to get the user-specified file path.

Here is an example showing how to use SaveFileDialogthe 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 SaveFileDialogobject saveFileDialog1and 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.FileNameget 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 SaveFileDialogthe detailed method of the control. If you have any further questions, please feel free to ask!

Guess you like

Origin blog.csdn.net/xiaogongzhu001/article/details/131112315