openFileDialog筛选器不显示任何选项,而是显示文件夹中的所有文件(即* .jpeg和* .xlsx)

Man*_*hak 0 c# excel openfiledialog

string file = "";
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
openFileDialog1.FilterIndex = 1;

if(result == DialogResult.OK) // Test result.
{
    file = openFileDialog1.FileName;
    try
    {
        string text = File.ReadAllText(file);
        size = text.Length;
    }
    catch(System.IO.IOException)
    {
    }
}

tempLBL.Text = file;
Run Code Online (Sandbox Code Playgroud)

我还测试了上面提到的过滤器。当我浏览...和显示所有文件时,它没有显示任何过滤器。我需要的是,当单击“浏览”按钮时,只有XLSX或XLS文件显示给用户。

提前致谢

Nik*_*wal 5

那是因为在设置过滤器和FilterIndex之前先显示对话框。

您的代码应该像

openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
openFileDialog1.FilterIndex = 1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
Run Code Online (Sandbox Code Playgroud)