openFileDialog 过滤器不显示任何选项并显示文件夹中的所有文件(即 *.jpeg 和 *.xlsx)
openFileDialog Filter not showing any option and showing all the files in the folder (i.e. *.jpeg and *.xlsx)
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;
我也测试了上面评论的过滤器。
当我浏览时它没有显示任何过滤器...并显示所有文件。我需要的是,当单击“浏览”按钮时,只会向用户显示 XLSX 或 XLS 文件。
提前致谢
那是因为您在设置过滤器和 FilterIndex 之前显示了对话框。
你的代码应该是这样的
openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
openFileDialog1.FilterIndex = 1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
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;
我也测试了上面评论的过滤器。 当我浏览时它没有显示任何过滤器...并显示所有文件。我需要的是,当单击“浏览”按钮时,只会向用户显示 XLSX 或 XLS 文件。
提前致谢
那是因为您在设置过滤器和 FilterIndex 之前显示了对话框。
你的代码应该是这样的
openFileDialog1.Filter = "Excel |*.xlsx"; //"Excel Files|(*.xlsx, *.xls)|*.xlsx;*.xls";
openFileDialog1.FilterIndex = 1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.