Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the files that can be selected using Open File Dialog box

I have a C# Windows Forms application where I load either a XML file or a CSV file for some task operations. When I click the Browse button I have, an 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#?

like image 436
user1501034 Avatar asked Aug 24 '12 11:08

user1501034


2 Answers

Use

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

this way only csv files or xml files are shown.

Odd-numbered pipes delineate between what's visible in the Filter dropdown and the corresponding actual file extension, and Even-numbered pipes delineate between the first entire file extension and the second.

For example, "CSV files (*.csv)|*csv" means users will see "CSV files (*.csv)" in the filter dropdown, and that option will look for any files that match *.csv.

In the line of code above, the pipe before "XML" indicates an entirely new filter option that will appear below the CSV option.

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.

like image 83
Stephan Schinkel Avatar answered Oct 31 '22 14:10

Stephan Schinkel


You can use the Filter property to let the user choose a certain type of file.

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.

You can do this with the Path.GetExtension() method.

like image 30
Gerald Versluis Avatar answered Oct 31 '22 14:10

Gerald Versluis