简体   繁体   English

限制可以使用“打开文件”对话框选择的文件

[英]Limiting the files that can be selected using Open FIle Dialog box

I got this C# windows forms application where I load either a XML file or a CSV file for some task operations. 我有这个C#windows窗体应用程序,我在其中加载XML文件或CSV文件进行某些任务操作。 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. 如果我加载JPG或ZIP文件或任何格式为CSV或XML以外的文件,我的应用程序崩溃。 Is there any way of limiting the Open File Dialog box to open only CSV or XMl files alone in C#? 有没有办法限制打开文件对话框只在C#中打开CSV或XMl文件?

use 采用

openFileDialog.Filter = "CSV files (*.csv)|*.csv|XML files (*.xml)|*.xml";

this way only csv files or xml files are shown. 这样只显示csv文件或xml文件。 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. 但是,如果用户输入完整的名称,用户也可以选择其他文件类型 - 因此请检查所选的文件名并相应地更正您的代码。

You can use the Filter property 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. 用户仍然可以在文件名框中输入'(star)。(star)'并显示所有文件。 So you should check the resulting file(s) in your code as well. 因此,您还应该检查代码中的结果文件。

You can do this with the Path.GetExtension() method. 您可以使用Path.GetExtension()方法执行此操作。

You can apply a filter in your Open file dialog which only shows .xml and csv files as mentioned above. 您可以在“打开文件”对话框中应用过滤器,该对话框仅显示上述.xml和csv文件。 With path.getextension http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx You can check if the user indeed selected a file with the right extension. 使用path.getextension http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx您可以检查用户是否确实选择了具有正确扩展名的文件。 If a wrong extension is selected, you can prompt to select a different file. 如果选择了错误的扩展名,则可以提示选择其他文件。

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... 如果选择了错误的文件,则不要继续上传/处理...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM