2

This seems like a really easy one but everything I try doesn't seem to work

say I have the following string:

string myString = "http://www.mysite.com/folder/file.jpg";

How can I process that to remove the URL and just leave "file.jpg" as the string value?

Thanks!

Kris

1
  • What would you like in the case of, e.g., http://example.com/test.php?key=val ? Or http://example.com/test.htm#section1 ? Commented Dec 1, 2010 at 0:37

2 Answers 2

10

You can always use System.IO.Path methods

string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg

If you do want to process more complex URIs you can pass it thought the System.Uri type and grab the AbsolutePath

string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);
Sign up to request clarification or add additional context in comments.

6 Comments

This is one of my favorite hacks :) Use it all the time for parsing network ID's.
Be aware that the separator characters used by Path.GetFileName are platform-dependent, so there's no guarantee that / will be in that set on every possible platform. (Having said that, I'm not aware of any platform where .NET runs that doesn't include / in the set.)
At the same time there is no promise that / is the correct delimting character for a URI. Path being dependant on the platform should get the correct Slash (as a note it supports both / and ``)... at least in the Microsoft version.
@Matthew: RFC2396 specifies that path segments in a URI are always delimited by /.
(Besides, if an RFC says to use /... wouldn't that imply that all versions of Path.GetFileName(...) would handle /)
|
4
string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);

Comments

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.