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

lookitskris
  • 678
  • 1
  • 6
  • 23
  • What would you like in the case of, e.g., `http://example.com/test.php?key=val` ? Or `http://example.com/test.htm#section1` ? – Domenic Dec 01 '10 at 00:37

2 Answers2

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);
Matthew Whited
  • 22,160
  • 4
  • 52
  • 69
  • This is one of my favorite hacks :) Use it all the time for parsing network ID's. – Metro Smurf Dec 01 '10 at 00:49
  • 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.) – LukeH Dec 01 '10 at 16:26
  • 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 Whited Dec 02 '10 at 01:38
  • @Matthew: RFC2396 specifies that path segments in a URI *are* always delimited by `/`. – LukeH Dec 02 '10 at 11:19
  • (Besides, if an RFC says to use `/`... wouldn't that imply that all versions of `Path.GetFileName(...)` would handle `/`) – Matthew Whited Dec 02 '10 at 22:35
  • @Matthew: No, because the RFC specifies URIs, which must always use the `/` delimiter. The `Path` class is designed to deal with filesystem paths, *not URIs*. The directory separator characters used by `Path` are implementation-defined (but by happy coincidence seem to always include `/` on all the .NET platforms that I've encountered). – LukeH Dec 02 '10 at 23:45
4
string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);
LukeH
  • 263,068
  • 57
  • 365
  • 409