Equivalent function for IO.Path.GetFileName for urls?

In .NET 4.0, what is the equivalent function for IO.Path.GetFileName for URLs?

+8
url
source share
4 answers

Uri class is your friend.

Provides an object representation of a single resource identifier (URI) and easy access to parts of a URI.

IsFile will try to determine if the Uri is actually pointing to a file.

Use the Segements property to get the file name (this will be the last segment).

 Uri uri = new Uri("http://example.com/title/index.htm"); var filename = uri.Segments[uri.Segments.Length - 1]; // filename == "index.htm" 
+13
source share

You can stick with creating a Uri object, or if you care about performance, use something similar to this:

  public class UriHelpers { public static string GetFileNameFromUrl(string url) { string lastSegment = url.Split('/').Last(); return lastSegment.Substring(0, lastSegment.IndexOf('?') < 0 ? lastSegment.Length : lastSegment.IndexOf('?')); } } 
+1
source share

You can use Server.MapPath () to map the physical path to the virtual path.

In addition, there are several methods in HTTPUtility that help you map out different types of paths.

0
source share

There are many ways: the main description here
Bucky exploiting the Uri class and, possibly, string tokenization, if necessary.

0
source share