0

I'm downloading files from the Internet inside of my application. Now I'm dealing with multiple file types so I need to able to detect what file type the file is before my application can continue. The problem that I ran into is that some of the URLs where the files are getting downloaded from contain extra parameters.

For example:

http://www.myfaketestsite.com/myaudio.mp3?id=20

Originally I was using String.EndsWith(). Obviously this doesn't work anymore. Any idea on how to detect the file type?

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
Edward
  • 7,346
  • 8
  • 62
  • 123

2 Answers2

3

Wrap the URL in a Uri class. It will split it up into different segments that you can use, or you can use the helper methods on the Uri class itself:

var uri = new Uri("http://www.myfaketestsite.com/myaudio.mp3?id=20");
string path = uri.GetLeftPart(UriPartial.Path);
// path = "http://www.myfaketestsite.com/myaudio.mp3"

Your question is a duplicate of:

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
  • What method should I use to accomplish this. Do I get the Query property and remove it from the original path? – Edward Oct 12 '11 at 20:02
  • @loyalpenguin: If you use the code above, the `path` variable will contain `http://www.myfaketestsite.com/myaudio.mp3`. – Cᴏʀʏ Oct 12 '11 at 20:04
0

You could always split on the question mark to eliminate the parameters. e.g.

string s = "http://www.myfaketestsite.com/myaudio.mp3?id=20";
string withoutQueryString = s.Split('?')[0];

If no question mark exists, it won't matter, as you'll still be grabbing the value from the zero index. You can then do your logic on the withoutQueryString string.

George Johnston
  • 31,652
  • 27
  • 127
  • 172