34

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,373
  • 5
  • 42
  • 54
M.Azad
  • 3,673
  • 8
  • 47
  • 77
  • 2
    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

60

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
  • 213,761
  • 22
  • 232
  • 286
11

What about

Path.GetExtension(ofd.FileName);
Aliostad
  • 80,612
  • 21
  • 160
  • 208
4

Use this:

Path.GetExtension(dialog.FileName);
ionden
  • 12,536
  • 1
  • 45
  • 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,373
  • 5
  • 42
  • 54
0

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

npinti
  • 51,780
  • 5
  • 72
  • 96
-2

Try this

fileDialog.File.Extension
Manu
  • 155
  • 1
  • 12