Question

I want to open file and check the type of file. I have a problem with Path.GetExtension. Is there other option to do this? I working in WPF. I tried with the following code

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 
dlg.Filter = "Image (*.bmp, *.jpg, *.gif, *.png)|*.bmp; *.jpg; *.gif; *.png|All (*.*)|*.*";
if (dlg.ShowDialog() == true) 
  string ext = Path.GetExtension(dlg.FileName); //problem
  if (ext == ".jpg")
    {...}

Error says:'System.Windows.Shapes.Path' does not contain a definition for 'GetExtension'

Was it helpful?

Solution

The problem is that WPF has a class called System.Windows.Shapes.Path (representing a drawing path), and you want System.IO.Path (for working with filesystem paths). Your file already has using System.Windows.Shapes. Adding using System.IO won't help because then the compiler won't know which Path you mean.

You can fix the problem by adding this line at the top of your file, which will tell the compiler that when you say Path you mean System.IO.Path.

using Path = System.IO.Path;

(Note: If you do this, you don't need using System.IO unless you're using other classes from System.IO.)

OTHER TIPS

Use string ext = System.IO.Path.GetExtension(dlg.FileName); and it will work fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top