簡體   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