【问题标题】:C# OpenFileDialog for getting a user-selected output path for a Windows form?C# OpenFileDialog 用于获取 Windows 窗体的用户选择的输出路径?
【发布时间】:2023-03-13 07:50:02
【问题描述】:

早上好,

我试图弄清楚如何正确使用 C# 中的 OpenFileDialog 函数来允许用户选择所需的输出文件夹。现在我的 Windows 窗体上有一个按钮和一个文本框。用户将点击按钮,这将在运行时打开对话框 GUI 以允许用户导航到输出位置,然后点击确定。然后他们应该通过在文本框中显示路径来确认他们的选择。

我现在的代码如下:

      private void button1_Click_3(object sender, EventArgs e)
    {
        OpenFileDialog OutputFilePath = new OpenFileDialog();

        string OutputString = OutputFilePath.FileName;
        FilePathBox.Text = OutputString;

    }

它编译得很好,但是当我点击按钮时,它没有弹出文件对话框。

我确定这很简单,我没有看到?

提前致谢!

~安德鲁

【问题讨论】:

  • 你应该打电话给OutputFilePath.ShowDialog,见MSDN中的例子msdn.microsoft.com/ru-ru/library/…
  • 以后,你应该先做一些研究。如果您只是随便看看,就不必在这里问问题了。
  • 一个快速的谷歌搜索会产生许多可以在线获得的工作示例,从而使您的声誉免于许多negative 点击

标签: c# .net openfiledialog


【解决方案1】:

您需要显示 Dialog 然后检查 DialogResult 因为用户可以单击取消

OpenFileDialog OutputFilePath = new OpenFileDialog();
var res = OutputFilePath.ShowDialog();
if (res == DialogResult.OK)
{
    string OutputString = OutputFilePath.FileName;
    FilePathBox.Text = OutputString;
}

【讨论】:

    【解决方案2】:

    你需要使用ShowDialog()

    private void button1_Click_3(object sender, EventArgs e)
    {
        using(OpenFileDialog OutputFilePath = new OpenFileDialog())
        {
             if(OutputFilePath.ShowDialog() == DialogResult.OK)
             {
                 string OutputString = OutputFilePath.FileName;
                 FilePathBox.Text = OutputString;
             }
        }
    
    }
    

    将对话框包装在 using 子句中将确保表单被垃圾回收。

    【讨论】:

      猜你喜欢
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-16
      • 2010-09-22
      • 2018-09-13
      相关资源
      最近更新 更多