Reputation: 5781
I used information from here http://msdn.microsoft.com/ru-ru/library/system.windows.forms.openfiledialog(v=vs.110).aspx
this way:
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".xml"; // this is how I get only required extension
dlg.Filter = "XML files (*.xml)|*.xml"; // I guess, this should be modified, don't know how.
dlg.InitialDirectory = _directoryName1;
// here we go
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string path = dlg.FileName;
In the Initial Directory I have to types of files of same xml
extension, which names begin with script-Data...
or GeneralParam...
. So I need to show in the OpenFileDialog only files, which names begin with script-Data...
.
I know, that I can notify user, what he has decided wrong file by parsing path
, but it isn't good solution for me. Is any other way out here?
Upvotes: 4
Views: 3621
Reputation: 7683
Try this.it will help you.if you want to filter file name starting with "script-Data" only sho in your application do this.
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Excel Files|script-Data*.xls;ascript-Data*.xlsx;script-Data*.xlsm";
of.ShowDialog();
Upvotes: 6
Reputation: 216243
Of course you can prepare your OpenFileDialog with the predefined settings expected, but
you can't prevent your user to type something totally different in the inputbox from the pattern expected. For example, if your user types "*.*"
in the input box and presses OK he/she can choose any file showed, but you could check what has been choosed WITHOUT EXITING the OpenFileDialog
and inform your user of the error.
All you need to do is to subscribe to the event FileOk
OpenFile dlg = new OpenFileDialog();
dlg.FileOk += CheckFileName;
dlg.InitialDirectory = _directoryName1;
dlg.Filter = "XML Files (*.xml)|*.xml";
dlg.FileName = "script-data*";
if(sdlg.ShowDialog() == DialogResult.OK)
{
Console.WriteLine("Open file:" + sdlg.FileName);
.....
}
void CheckFileName(object sender, System.ComponentModel.CancelEventArgs e)
{
OpenFileDialog dlg = (sender as OpenFileDialog);
if(Path.GetExtension(dlg.FileName).ToLower() != ".xml")
{
e.Cancel = true;
MessageBox.Show("Please choose files with the extension 'XML'");
return;
}
if(!Path.GetFileName(dlg.FileName).ToLower().StartsWith("script-data")
{
e.Cancel = true;
MessageBox.Show("Please choose files that starts with 'script-data'");
return;
}
}
Upvotes: 2
Reputation: 26199
you have already set the Filter
property. so you can see only .xml
files when OpenFileDialog
opens. but if you want to filter
the filenames
to be displayed in OpenFileDialog
you can set the FileName
property as there is no other option to filter
by filename
Try This:
dlg.FileName = "script-Data*";
Upvotes: 4