【问题标题】:How to show OpenFileDialog selected directory in a textbox如何在文本框中显示 OpenFileDialog 选定的目录
【发布时间】:2016-09-03 06:35:31
【问题描述】:

所以,我设置了一个文件浏览器,可以正常工作。 但是现在我想把你去的结束位置放到一个文本框中。如果用户想手动输入文件位置,仍然可以输入。

  private void button1_Click(object sender, EventArgs e)
    {
        int size = -1;
        DialogResult result = openFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string file = openFileDialog1.FileName;
            try
            {
            string text = File.ReadAllText(file);
            size = text.Length;
            }
            catch (IOException) { }
        }

        Console.WriteLine(size);
        Console.WriteLine(result);
   }

【问题讨论】:

  • 你能解释得更详细更具体吗?
  • 好吧,基本上,我有一个设置选项卡,我想要一个文本框。在文本框旁边,我有一个“浏览”按钮,可以打开文件浏览器。现在用户选择文件后,我希望该文件的方向显示在文本框中

标签: c# .net file directory openfiledialog


【解决方案1】:

可以获取完整路径

textBox1.Text = file;

以及最后一个文件夹名称

string lastFolderName = Path.GetFileName(Path.GetDirectoryName(file));
textBox1.Text = lastFolderName;

在您的代码中,您可以像下面这样使用,如果您想使用另一个范围内的位置,则将 file 变量设为全局

string file = "";            
private void button1_Click(object sender, EventArgs e)
    {
       int size = -1;
       DialogResult result = openFileDialog1.ShowDialog();
       if (result == DialogResult.OK)
        {
           file = openFileDialog1.FileName;
           try
           {
              string text = File.ReadAllText(file);
              size = text.Length;
              textBox1.Text = file; // for full location
              textBox2.Text = Path.GetFileName(Path.GetDirectoryName(file)); // for last folder name
           }
           catch (IOException)
           {
           }
       }
    }

然后

 private void textBox1_TextChanged(object sender, EventArgs e)
        {
           textBox2.Text = file;
        }  

【讨论】:

  • 所以,textBox1.Text = 文件;在我希望目录显示的文本框下?
  • 是的,它是您要显示目录的文本框
  • 出于某种原因 textBox1.Text = file;文件在当前上下文中不存在截至目前我得到:imgur.com/QhMNLL9
  • 你已经在按钮点击事件中完成了所有操作并尝试从另一个 textchange 事件中访问它,这是不允许的,你必须使文件变量全局范围,目前它在本地范围内跨度>
  • 我该怎么做呢? + 你对所有的帮助都很了不起。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多