繁体   English   中英

c#获取文件名

[英]c# Get File Name

private void button1_Click(object sender, EventArgs e)
    {


        OpenFileDialog newOpen = new OpenFileDialog();

       DialogResult result = newOpen.ShowDialog();

       this.textBox1.Text = result + "";

    }

它只是返回“OK”

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

您需要访问文件名:

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

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

您需要读取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.GetFileName(file):返回文件名

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM