C# winform中选择本地文件,并获取其路径

 
 private void button1_Click(object sender, EventArgs e)
 {
      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)
      {
          this.textBox1.Text = openFileDialog1.FileName;   //显示文件路径
      }
 }


注:如果指定某一个格式,例如后缀为.txt格式的文件,代码可改写为:

openFileDialog1.Filter = "(*.txt)|*.txt";

你可能感兴趣的:(C# winform中选择本地文件,并获取其路径)