OpenFileDialog.DefaultExt返回一个空字符串

时间:2014-07-10 18:42:29

标签: c# openfiledialog

我目前正在尝试使用文件对话窗口来保存Excel的完整文件路径。我想测试该文件是一个实际的Excel文件。目前,当我在OpenFileDialog.DefaultExt中使用该属性时,下面显示的代码返回一个空字符串。当我通过字符串调试它是空的时,属性应该包含扩展名。有没有人理解为什么这个属性是空的,我希望它包含" xlsx"

我手头有什么东西可以设置这个属性吗?

  private void Browse_for_Excel_Click(object sender, EventArgs e)
    {
        //Want to bring up a window that allows you to select an Excel File

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.ShowDialog();

        bool FileISGood = openFileDialog1.CheckFileExists;
        bool FilePathGood = openFileDialog1.CheckPathExists;


        string FileName = openFileDialog1.SafeFileName;
        string extension=openFileDialog1.DefaultExt;  //Returns an empty string @""
        Console.WriteLine(extension);
        if( (FileISGood == true && FilePathGood ==true) &&  (extension==@"xlsx")   )  {

            Console.WriteLine("insiide if statemetn");

        }


    }

1 个答案:

答案 0 :(得分:0)

当文件名不包含任何扩展名时,创建文件时使用DefaultExt属性。

尝试使用Filter property限制对话框列表中可查看的文件:

using (OpenFileDialog openFileDialog1 = new OpenFileDialog()) {
  openFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx";
  if (openFileDialog1.ShowDialog() == DialogResult.OK) {
    // do work...
  }
}