Edward
Edward

Reputation: 7424

How to handle paths to files with extra parameters in C#?

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?

Upvotes: 0

Views: 110

Answers (2)

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107518

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:

Upvotes: 3

George Johnston
George Johnston

Reputation: 32258

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.

Upvotes: 0

Related Questions