【问题标题】:Write path of the file chosen in the FileDialog在 FileDialog 中选择的文件的写入路径
【发布时间】:2021-11-26 00:09:22
【问题描述】:

我已经制作了一个 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# windows winforms


    【解决方案1】:

    而不是将DialogResult的对象存储到test.txt,而是存储用户喜欢选择的FileName

    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 Property

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

    【讨论】:

    • 严重代码描述项目文件行抑制状态错误 CS1061“DialogResult”不包含“FileName”的定义,并且找不到接受“DialogResult”类型的第一个参数的可访问扩展方法“FileName” (您是否缺少 using 指令或程序集引用?) FormChooseFolder
    • FileName 是属性而不是方法,你能说明你是如何调用FileName
    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多