ASP.NET VERSIONS: 1.0 | 1.1
Parse File Paths and URLs in a Heartbeat
Make your life easier by using the Path class to work with drive paths, UNC paths, and URLs.
By Brian Noyes
If you ever find yourself suspecting a programming task might be something programmers often have to do, start looking in the .NET Framework class library for an existing solution. The .NET architects have done an awesome job of including classes in the .NET Framework for most common tasks.
Of course, one of the most common tasks programmers have to perform is extracting portions of a file path or URL to use in their application business logic. Sure enough, the Path class - which lives in the System.IO namespace - has static (Shared in VB .NET) methods that let you perform many operations to work with paths that contain drive paths, universal naming convention (UNC) paths, or URLs. You easily can extract the relevant portions of the path using these methods, or you can construct paths on the fly and let the Path class worry about getting the right path separators in between the parts.
The following code demonstrates some of the Path class's most useful methods. The snippet uses the Debug.Assert method to ensure the results returned from the Path methods are the ones you expect. It also demonstrates the use of the Combine method, which you can use to build up a path from individual parts, but you don't have to worry about providing the path separators; the Path class looks to see if one is provided already, and it inserts one for you if needed:
string filePath = @"C:\temp\myapp\whatever.config";
Debug.Assert(Path.GetPathRoot(filePath) == @"C:\");
Debug.Assert(Path.GetExtension(filePath) == ".config");
string part1 = @"C:\temp";
string part2 = "myapp";
string part3 = "whatever.aspx";
string result = Path.Combine(part1,part2);
result = Path.Combine(result, part3);
The Path class many other methods besides the ones shown here. You can specify what the path separator should be (it defaults to "\") with the PathSeparator property. You can change the file extension without parsing using the ChangeExtension method. You can check what the invalid characters are for a path using the InvalidPathChars property.
Any time you need to manipulate or parse a path in .NET, first check out this class to see if it can meet your needs. Don't waste time writing code to detect slashes and dots when you could be writing real business logic instead.
Brian Noyes is an associate of IDesign Inc. (http://www.idesign.net) and a trainer, consultant, and writer. He's a Microsoft Certified Solution Developer with more than 12 years of programming, design, and engineering experience. Brian specializes in .NET architecture, design, and coding of data-driven Web and Windows applications, data-access and XML technologies, and Office automation. He is a contributing editor for asp.netPRO and other publications. E-mail him at mailto:[email protected].