openFileDialog与saveFileDialog的使用

private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = openFileDialog1.FileName;
                txtInfo.Clear();
                txtInfo.Text = File.ReadAllText(fileName);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileName = saveFileDialog1.FileName;
                File.WriteAllText(fileName, txtInfo.Text);
            }
        }

 

C# 的 `SaveFileDialog` 和 `OpenFileDialog` 是用来让用户选择文件的对话框控件。下面是它们的基本使用方法: ### SaveFileDialog ```csharp SaveFileDialog saveFileDialog1 = new SaveFileDialog(); saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; // 设置文件类型过滤器,只显示 txt 文件和所有文件 saveFileDialog1.FilterIndex = 1; // 设置默认选中的文件类型 saveFileDialog1.RestoreDirectory = true; // 记录用户打开的目录路径 if (saveFileDialog1.ShowDialog() == DialogResult.OK) // 显示对话框并判断用户是否点击了确认按钮 { // 获取用户选择的文件路径 string filePath = saveFileDialog1.FileName; // 将数据保存到文件中 // ... } ``` ### OpenFileDialog ```csharp OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"; // 设置文件类型过滤器,只显示 txt 文件和所有文件 openFileDialog1.FilterIndex = 1; // 设置默认选中的文件类型 openFileDialog1.RestoreDirectory = true; // 记录用户打开的目录路径 if (openFileDialog1.ShowDialog() == DialogResult.OK) // 显示对话框并判断用户是否点击了确认按钮 { // 获取用户选择的文件路径 string filePath = openFileDialog1.FileName; // 读取文件中的数据,并进行处理 // ... } ``` 以上代码中,`Filter` 属性用来设置文件类型过滤器,只显示指定类型的文件。`FilterIndex` 属性用来设置默认选中的文件类型。`RestoreDirectory` 属性用来记录用户打开的目录路径,下次打开对话框时会自动打开该目录。`ShowDialog()` 方法用来显示对话框,并返回一个 `DialogResult` 枚举值,表示用户点击了哪个按钮(OK、Cancel 等)。如果用户点击了 OK 按钮,则可以通过 `FileName` 属性获取用户选择的文件路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值