【问题标题】:Remove path to file from textbox when file selected C# Visual Studio选择文件时从文本框中删除文件路径 C# Visual Studio
【发布时间】:2017-01-02 21:15:18
【问题描述】:

您好,我正在尝试从我的 Windows 窗体应用程序的目录中选择一个文件,但我似乎找不到任何可以从文本框中删除路径并仅保留文件名的内容(例如:“C: \Users\Users\Documents\File.txt" 将只是 "File.txt") 选择文件时保存输出的位置。

         OpenFileDialog openFileDialog1 = new OpenFileDialog();

         openFileDialog1.InitialDirectory = @"C:\OUTPUT";
         openFileDialog1.Title = "Browse exe Files";

         openFileDialog1.CheckFileExists = true;
         openFileDialog1.CheckPathExists = true;
         openFileDialog1.Filter = "exe files | *.exe";

         openFileDialog1.DefaultExt = "exe";
         openFileDialog1.FilterIndex = 2;
         openFileDialog1.RestoreDirectory = true;

         openFileDialog1.ReadOnlyChecked = true;
         openFileDialog1.ShowReadOnly = true;

         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             textBox6.Text = openFileDialog1.FileName;
         }

谁能告诉我如何做到这一点?

谢谢

【问题讨论】:

  • 只是澄清一下,因为我有点不清楚您的具体问题是什么:路径名称显示在对话框的文本框中,并且您希望文本框为空白?
  • @MathSquared OP 想要的是删除文件的路径并只保留它的名称。示例“C:\Users\MyUser\Documents\Text.txt”就是“Text.txt”

标签: c# select path dialog openfiledialog


【解决方案1】:

您可以为此使用Path.GetFileName 函数。

 textBox6.Text = System.IO.Path.GetFileName(openFileDialog1.FileName);

【讨论】:

  • 我这样做了:字符串路径 = @"C:\OUTPUT";它给了我这个错误:'string'不包含'GetFileName'的定义,并且找不到接受'string'类型的第一个参数的扩展方法'GetFileName'(您是否缺少 using 指令或程序集引用? )
  • Path 不是字符串变量,而是类名。我编辑了答案以使其更清楚。
猜你喜欢
  • 2012-10-13
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
相关资源
最近更新 更多