You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Winform使用OpenFileDialog如何将选中文件路径写入TXT文件

问题原因

你写入文件的对象是DialogResult枚举类型的变量dr,当用户点击文件选择框的确认按钮时,dr的值为DialogResult.OK,转为字符串写入后就只会显示"OK",你没有读取文件选择框返回的选中文件路径属性。
另外你的代码存在重复实例化OpenFileDialog的问题:方法内手动new的openFileDialog1对象没有被实际使用,后续调用的是窗体设计器生成的this.openFileDialog1实例,前面的实例化代码无效可删除。

修正后的代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace FormChooseFolder
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 直接使用设计器生成的openFileDialog1实例,设置属性
            this.openFileDialog1.InitialDirectory = @"C:\";
            this.openFileDialog1.Title = "Select Files";
            this.openFileDialog1.CheckFileExists = true;
            this.openFileDialog1.Multiselect = true;

            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == DialogResult.OK)
            {
                // 使用using自动释放StreamWriter资源,无需手动调用Close
                using (TextWriter txt = new StreamWriter("C:\\test.txt"))
                {
                    // 遍历所有选中的文件路径,逐个写入,每行一个路径
                    foreach (string filePath in this.openFileDialog1.FileNames)
                    {
                        txt.WriteLine(filePath);
                    }
                }
            }
        }
    }
}

核心修改说明

  • 从OpenFileDialog的FileNames属性读取所有选中文件的全路径,如果你只需要单选可以直接使用FileName属性获取单个路径
  • 用using语句管理StreamWriter的生命周期,自动处理资源释放,避免文件句柄泄露
  • 按行写入多个文件路径,你可以根据需求调整分隔格式
  • 注意:写入C盘根目录需要程序有管理员权限,运行报错时可以将输出路径改为其他普通目录(如我的文档、桌面等)

内容的提问来源于stack exchange,提问作者ThePyyDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:09:01