c# 获取文件名

本文关键字:文件名 获取 | 更新日期: 2023-09-27 18:35:25

private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog newOpen = new OpenFileDialog();
       DialogResult result = newOpen.ShowDialog();
       this.textBox1.Text = result + "";
    }

它只返回"确定"

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

c# 获取文件名

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

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;
        }
    }

您需要访问文件名:

 string filename = newOpen.FileName;

或文件名(如果允许多个文件选择):

newOpen.FileNames;

参考: 打开文件对话框类

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);
        }
    } 
}
您需要

读取OpenFileDialog实例的 FileName 属性。这将获取所选文件的路径。

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

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.Get文件名(文件):返回文件名