首页 > 解决方案 > 在 FileDialog 中选择的文件的写入路径

问题描述

我制作了一个 WindowsForms 程序:

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)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog
            {
                InitialDirectory = @"C:\",
                Title = "Browse Text Files",

                CheckFileExists = true,
            };


            this.openFileDialog1.Multiselect = true;
            this.openFileDialog1.Title = "Select Files";

            DialogResult dr = this.openFileDialog1.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                TextWriter txt = new StreamWriter("C:\\test.txt");
                txt.Write(dr);
                txt.Close();
            }
        }
    }
}

应该将选择的文件的路径写入test.txt,但它会写入OK。有什么办法可以让它像这样显示所选文件的路径C:\Pictures\banana.png吗?

标签: c#windowswinforms

解决方案


而不是存储用户选择DialogResult的存储对象,test.txtFileName

DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
     TextWriter txt = new StreamWriter("C:\\test.txt");
     txt.Write(dr.FileName);  //Use FileName property to get entire file path
     txt.Close();
}

MSDN 文档:FileDialog.FileName 属性

获取或设置一个字符串,该字符串包含在文件对话框中选择的文件名。


推荐阅读