29

I want just get Image(.JPG,.PNG,.Gif) File from my OpenFileDialog How can I get file extension from OpenFileDialog?

Is it impossible?

Ali
  • 3,057
  • 4
  • 33
  • 50
M.Azad
  • 3,485
  • 7
  • 43
  • 72
  • 1
    Yes, the Filter property allow you to preselect the file types required, look at my updated answer below – Steve Mar 26 '12 at 12:17
  • Curious, I'm sure you have asked about the Filter property, but you have accepted another answer. – Steve Mar 27 '12 at 18:12
  • @Steve you are right. I have a mistake.I change my accepted answer – M.Azad Mar 28 '12 at 06:54

6 Answers6

56

To filter only certain types of file use Filter Property

OpenFileDialog1.Filter = "Image Files (JPG,PNG,GIF)|*.JPG;*.PNG;*.GIF";

To get the file extension use the Path helper GetFileExtension

if (OpenFileDialog1.ShowDialog() == DialogResult.OK)
   string ext = Path.GetExtension(OpenFileDialog1.FileName);
Steve
  • 203,265
  • 19
  • 210
  • 265
11

What about

Path.GetExtension(ofd.FileName);
Aliostad
  • 76,981
  • 19
  • 152
  • 203
4

Use this:

Path.GetExtension(dialog.FileName);
ionden
  • 11,758
  • 1
  • 41
  • 37
1

Also could use Extension Method as blow:

public static class Helper
    {
        public static string GetFileExtention(this OpenFileDialog dialog)
        {
            return Path.GetExtension(dialog.FileName);
        }
    }

And simply use it by:

 openFileDialog1.ShowDialog();
 string foo = openFileDialog1.GetFileExtention();
Ali
  • 3,057
  • 4
  • 33
  • 50
0

As stated in here, you can do something like this: Path.GetExtension(photoFile.FileName)

npinti
  • 50,175
  • 5
  • 67
  • 92
-2

Try this

fileDialog.File.Extension
Manu
  • 145
  • 1
  • 11