0
private void button1_Click(object sender, EventArgs e)
    {


        OpenFileDialog newOpen = new OpenFileDialog();

       DialogResult result = newOpen.ShowDialog();

       this.textBox1.Text = result + "";

    }

它只是返回“OK”

我究竟做错了什么?我希望获取文件的 PATH 并将其显示在文本框中。

4

4 回答 4

1

ShowDialog方法返回用户是否按下OKCancel。这是有用的信息,但实际文件名作为属性存储在对话框中

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog newOpen = new OpenFileDialog();
        DialogResult result = newOpen.ShowDialog();
        if(result == DialogResult.OK) {
              this.textBox1.Text = newOpen.FileName;
        }
    }
于 2013-10-14T23:43:03.433 回答
1

您需要访问文件名:

 string filename = newOpen.FileName;

或文件名,如果您允许选择多个文件:

newOpen.FileNames;

参考:OpenFileDialog 类

private void button1_Click(object sender, System.EventArgs e) {
    Stream myStream = null;
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
    openFileDialog1.FilterIndex = 2 ;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        try
        {
            if ((myStream = openFileDialog1.OpenFile()) != null)
            {
                using (myStream)
                {
                    // Insert code to read the stream here.
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: Could not read file. Error: " + ex.Message);
        }
    } 
}
于 2013-10-14T23:41:26.397 回答
0

您需要阅读实例的FileName属性。OpenFileDialog这将为您提供所选文件的路径。

于 2013-10-14T23:41:36.203 回答
0

以下是使用现有文件作为默认文件并获取新文件的示例:

private string open(string oldFile)
    {
        OpenFileDialog newOpen = new OpenFileDialog();
        if (!string.IsNullOrEmpty(oldFile))
        {
          newOpen.InitialDirectory = Path.GetDirectoryName(oldFile);
          newOpen.FileName = Path.GetFileName(oldFile);
        }

        newOpen.Filter = "eXtensible Markup Language File  (*.xml) |*.xml"; //Optional filter
        DialogResult result = newOpen.ShowDialog();
        if(result == DialogResult.OK) {
              return newOpen.FileName;
        }

        return string.Empty;
    }

Path.GetDirectoryName(file) : 返回路径

Path.GetFileName(file) : 返回文件名

于 2013-10-14T23:55:31.230 回答