-2

我在下面编写了仅选择 pdf 文件的代码,但它不起作用。

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

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

4

2 回答 2

11

您需要Filter 在打开对话框之前设置第一个。

OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "Pdf files (*.Pdf)|*.Pdf"; //this should be before
fd.ShowDialog();
于 2013-04-15T10:31:36.400 回答
1

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
}

希望这可以帮助

于 2013-04-15T10:56:27.843 回答