C# 打开文件对话框问题

C# 打开文件对话框问题,c#,C#,我写了下面的代码,只选择pdf文件,但它不工作 OpenFileDialog fd = new OpenFileDialog(); fd.ShowDialog(); fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; 请帮助,这有什么问题吗?在打开对话框之前,您需要先设置过滤器 OpenFileDialog fd = new OpenFileDialog(); fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; //this should b

我写了下面的代码,只选择pdf文件,但它不工作

OpenFileDialog fd = new OpenFileDialog();
fd.ShowDialog();
fd.Filter = "Pdf files (*.Pdf)|*.Pdf";

请帮助,这有什么问题吗?

在打开对话框之前,您需要先设置
过滤器

OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; //this should be before
fd.ShowDialog();

Habib有正确的答案,但我觉得我应该补充一点,您应该检查对
ShowDialog
的响应,以确保用户没有取消对话框。如果他们在没有选择文件的情况下取消对话框,则
OpenFileDialog
将显示文件名为“”,这在应用程序的其余部分中不会有用

示例

OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "PDF Files(*.pdf)|*.pdf";
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    // Do stuff here
}
else
{
    // The user cancelled the request to select a PDF
}

希望这有帮助

在调用
ShowDialog()
之前尝试设置过滤器。事后设置它不会像您预期的那样起作用。