I'm learning C and C#, this question is for C#. I have a app that I want to open files on my C:\ drive. Can I use OpenFileDialog to open any type of file? How is this done?
Here is the code:
case 1:
openSomething();
break;
private static void openSomething()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files (*.*)|*.*";
open.ShowDialog();
if (open.ShowDialog() == DialogResult.OK)
{
File.Open(open.FileName); // I want to do something like this
}
}
Is there something like System.Diagnostics.Process.Start on programs for files, so I use openfiledialog to get the filename and then my code opens the file with the default application?
Edit: I answered my own question
private static void openSomething()
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "All Files (*.*)|*.*";
if (open.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(open.FileName);
}
}
Usually the program tries to limit the kind of files listed by OpenFileDialog using the Filter property, but, if you want to allow the opening of any kind of file you set this property (before calling ShowDialog) with something like this
open.Filter = "All Files (*.*)|*.*";
meaning that every kind of file could be choosen by your user.
Keep in mind that the Filter property is just a facility to give a rapid choice to the end user, by itself the OpenFileDialog can open any kind of files also if you set any specialized filter.
All that your user is required to do is typing the *.*
in the filename textbox space and he/she can choose any kind of file (of course only if he/she has the required file/folder access permissions)
After the ShowDialog returns DialogResult.OK you could check if there is something selected in the Filename property, and, if you want to open the file using the default application associated for the file extension then you use Process.Start
if (open.ShowDialog() == DialogResult.OK)
{
if(open.FileName.Trim() != string.Empty)
{
Process.Start(open.FileName);
}
}
Of course this could be problematic if the file choosen has no default program associated (for example what if the user choose a DLL?), so perhaps it is better to apply a filter to select only a subset of well known file types. But this depends on your requirements.