Some things should just be simple like extracting a filename from a file path. Like suppose we have this painful URL (http://www.mydomain.com/archive/articles/techology/programming/aspnet-101.aspx), and we want to trim this down to just the good stuff, aspnet-101.aspx. Well we could always write a regular expression to cut its teeth on this or even slice and dice through it by dividing it into substrings keying off the forward slash. Though its not its exactly brain surgery, its still more effort than I want to devote to this rather mundane task. Thankfully, ASP.NET makes life easy via the System.IO.Path namespace. Specifically, we are going to focus on Path.GetFileName in the following code:
Now tell me it doesn’t get much easier than that. First, we do a quick check to ensure that sFileName is a URL then we run it through the Path.GetFileName which spits back our result. Path has a handful of helpful methods for massaging those file names so give them a look.
↧