C# 限制可以使用打开文件对话框选择的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12108628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting the files that can be selected using Open FIle Dialog box
提问by user1501034
I got this C# windows forms application where I load either a XML file or a CSV file for some task operations. I got a Browse button. When I click the Browse button, Open File Dialog box appears and I can navigate to a location on my drive and choose the file and then upload it using an Upload button. If I load a JPG or a ZIP file or any file whose format is anything except CSV or XML, my application crashes. Is there any way of limiting the Open File Dialog box to open only CSV or XMl files alone in C#?
我得到了这个 C# windows 窗体应用程序,我在其中加载了 XML 文件或 CSV 文件以进行某些任务操作。我有一个浏览按钮。当我单击“浏览”按钮时,会出现“打开文件”对话框,我可以导航到驱动器上的某个位置并选择文件,然后使用“上传”按钮上传它。如果我加载 JPG 或 ZIP 文件或任何格式不是 CSV 或 XML 的文件,我的应用程序就会崩溃。有没有办法限制打开文件对话框在 C# 中只打开 CSV 或 XMl 文件?
采纳答案by Stephan Schinkel
use
用
openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";
this way only csv files or xml files are shown. but nevertheless users can also select other filetypes if they type in the complete name - so check the filename that was selected and correct your code accordingly.
这样只显示 csv 文件或 xml 文件。但是,如果用户输入完整名称,他们也可以选择其他文件类型 - 因此请检查所选的文件名并相应地更正您的代码。
回答by Gerald Versluis
You can use the Filterproperty to let the user choose a certain type of file.
您可以使用该Filter属性让用户选择某种类型的文件。
However! This is not a guarantee. A user is still able to input '(star).(star)' in the filename box and show all files. So you should check the resulting file(s) in your code as well.
然而!这不是保证。用户仍然可以在文件名框中输入 '(star).(star)' 并显示所有文件。因此,您还应该检查代码中的结果文件。
You can do this with the Path.GetExtension()method.
你可以用这个Path.GetExtension()方法来做到这一点。
回答by Hunterseaker
You can apply a filter in your Open file dialog which only shows .xml and csv files as mentioned above. With path.getextension http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspxYou can check if the user indeed selected a file with the right extension. If a wrong extension is selected, you can prompt to select a different file.
您可以在“打开文件”对话框中应用过滤器,该过滤器仅显示上述 .xml 和 csv 文件。使用 path.getextension http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx您可以检查用户是否确实选择了具有正确扩展名的文件。如果选择了错误的扩展名,您可以提示选择不同的文件。
I would strongly recommend to check the file extension before upload. Just check the extension after the user had selected the file. If the wrong files was selected, just don't continue the upload/processing...
我强烈建议在上传前检查文件扩展名。只需在用户选择文件后检查扩展名。如果选择了错误的文件,请不要继续上传/处理...

