Reputation: 8865
I have to open a file dialog. In that I have to choose one file either an XML or MAP file. If the choosen file is MAP file then I have to do step-A or if the choosen file is XML then I have to do step-B. My question is how to know which file is selected from the dialog box application?
OpenFileDialog fileDialog1 = new OpenFileDialog();
fileDialog1.Filter = "XML Files|*.xml|MAP Files|*.map";
fileDialog1.ShowDialog();
How to know which file is selected from the above filter ?
Upvotes: 0
Views: 2016
Reputation: 164
Well, the above answers will work if luckily all the filters have different extensions. but if we are talking about different File versions with the same extension then we can get the selected filter through this code:
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "Excel 97|*.xls|Excel 95|*.xls";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Filer index is 1 based.
switch (dlg.FilterIndex)
{
case 1:
//Filter name: Excel 97
break;
case 2:
//Filter name: Excel 95
break;
}
}
Upvotes: 0
Reputation: 4737
You could even use similar extensions in a switch with stacked labels and use the default case for unsupported file types:
switch (extension)
{
case "xml":
case "xaml":
Debug.WriteLine("It's an XML!");
break;
case "map":
Debug.WriteLine("It's a map!");
break;
default:
MessageBox.Show("Please select an XML or MAP file");
// Show the dialog again
break;
}
Upvotes: 0
Reputation: 48568
I think you can't do that while it is open.
When user presses OK then pass OpenFileDialog.Filename
in Path.GetExtension
method or OpenFileDialog.Filename.Endswith(".xml")
.
Check if extension is XML then do x
step otherwise y
step.
EDIT
See for functionality that you require, there has to be an event in open file dialog.
There are 2 OpenFileDialog
Class
System.Windows.Forms
Microsoft.Win32
Both have only one event OpenFileDialog.FileOK
which you can look for.
Upvotes: 1
Reputation: 2348
openFileDialog1.FileName = "";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string filename = openFileDialog1.FileName;
if (File.Exists(filename))
{
//do something here
}
}
The FileName attribute of OpenFileDialog is the file name selected.
Upvotes: 0
Reputation: 4468
You can use:
string fileName = OpenFileDialog.Filename;
if(fileName.EndsWith(".xml"))
{
//
}
else if(fileName.EndsWith(".map"))
{
//
}
Upvotes: 2