7

If the user provides the url path to the image, i want to be able to try and download it with with a Webclient. I am using a httpresponse to check the file. Is there a way to grab the file name to make it easier to save? Thanks

2 Answers 2

8

Try using the Uri Class to load the path and pull the file name from the Segments collection:

Uri uri = new Uri("http://www.domain.com/image.jpg");
string fileName = uri.Segments.Last();
Sign up to request clarification or add additional context in comments.

6 Comments

I thought about that, and one of the elements is what I need but how would I know that, lets say element 5 was the right one to pull for the image name and type? and what if the image has querystrings does that count in the segment?
I thought you needed to pull the image file name? This would (AFAIK) be the last segment in the URL. This approach worked for me when testing it.
Yes this would work for me as well if the last segment is always the filename segment. Lets say that the path was www.image.com/testimage.png?test=1&name=joe Will the last segment in the array be testimage.png? If so this is a winner!
See the Remarks section from: Uri.Segments Property It states that "The Segments property returns an array of strings containing the "segments" (substrings) that form the URI's absolute path." Later on it states "A URI's absolute path contains everything after the host and port and before the query and fragment.". So from this it seems that the very last segment should be the file name (in a URL to an image).
Thanks for the insight, this will work for me perfectly then.
|
3

I would look into using System.IO.Path.GetFileName for this:

string fileName = Path.GetFileName("http://www.abc.com/myimage.jpg");

3 Comments

The only trouble with this approach is it would include the query string arguments with the file name. So passing "http://www.abc.com/myimage.jpg?param1=abc" would return "myimage.jpg?param1=abc".
@jdavies: Are you sure about that? There shouldn't be any parameters when specifying a path to an image either, should there?
I suppose it could be possible that an HttpHandler had been setup, to serve different images based on the parameters? (I know its unlikely :)) Either way it was a concern for the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.