When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, May 25, 2005

Little Known, Invaluable Methods and Properties in the .NET Framework Base Class Library : Working with File Paths

By Scott Mitchell


Introduction


There was a simpler time in history when one could know all intricacies in their given field. An experienced cobbler in yesteryear could feasibly know all there is to cobbling with the materials they had available. With the depth and breadth of knowledge today, however, such mastery of any given topic is virtually impossible, requiring people to tightly focus in on particular aspects of a given field. For example, if you are reading this article you are likely a Web developer using Microsoft's Web technologies. From a big picture view that encompasses the totality of the field of computer science, you are working in a very specific niche.

Even within this particular, focused realm of ASP.NET development, the breadth and depth of tools available are still astounding and overwhelming. I've used Visual Studio .NET countless times over the years and still am finding out new tips and tricks. (See Getting the Most Out of Visual Studio .NET for a list of some of my favorite tips and productivity enhancements!) Additionally, the .NET Framework Base Class Library (BCL) contains a slew of useful methods that, I've found, are beneath the radar for most ASP.NET developers.

This article provides a listing of those .NET Framework BCL methods and properties that are quite handy but not well-known. I'd like this article to be a work in progress, so if you know of any .NET Framework methods or properties you consider not in every ASP.NET developer's lexicon, but should be, let me know! Each week I plan to add additional useful methods and properties focused in a particular area. This week's tips and tricks focus on working with file paths. Read on to learn more!

- continued -

The List...


I plan on adding additional topics to this list. The first topic is Working with File Paths. (If you have any suggested methods or properties that you think are not well-known, but invaluable, please be sure to let me know.)

Little Known, Invaluable Methods and Properties in the .NET Framework BCL
  Working with File Paths (Working with Colors) Next -->
The .NET Framework contains a Path class in the System.IO namespace that has a bevy of useful, static properties and methods for working with file paths. If you come from a classic ASP background, you've no doubt written code that parses a string file path, extracting the filename, or perhaps just the extension. These sorts of mundane, error-prone file parsing techniques are no longer needed - just let the Path class do the dirty work for you! (Note: not all of the Path class's members are enumerated below; refer to the technical documentation for a thorough list.)
Visit the Technical Docs for the Path Class...
Path.Combine(string, string) Combines two paths together, returning a single string path. This is useful if you have a directory path and a file path, and you want to combine them into a single, complete path. For example, imagine you have the string "C:\Inetpub\wwwroot\MyApp" and "Images\Skyline.jpg", and you want to combine them into one, complete path - C:\Inetpub\wwwroot\MyApp\Images\Skyline.jpg. A simple string concatenation would work here, injecting a \ between the two strings, but what if there was a \ after MyApp? These are conditions we'd need to test for.

Rather than having to futz around with the various permutations, adding or removing backslashes, just use Path.Combine() - it will handle all of these cases. Example syntax:

'VB.NET...
Dim completePath as String = _
   System.IO.Path.Combine("C:\MyApp", "Images\Skyline.jpg")

// C#...
string completePath = 
   System.IO.Path.Combine(@"C:\MyApp", @"Images\Skyline.jpg");

Be sure to heed the Remarks section of the Path.Combine(path1, path2) method's technical documentation:

If path1 does not end with a valid separator character as defined in DirectorySeparatorChar, AltDirectorySeparatorChar, or VolumeSeparatorChar, DirectorySeparatorChar is appended to path1 before concatenation.

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

So, if the second input parameter starts with a \, just the second input parameter will be returned.
Path.GetExtension(string) Have a filepath and want to know the extension of the file? The GetExtension(string) method will return precisely that. No more picking through the string trying to find the last period. Example syntax:

'VB.NET... Returns ".jpg"
Dim fileExtension as String = _
   System.IO.Path.GetExtension("C:\MyApp\Images\Skyline.jpg")

// C#...  Returns ".jpg"
string fileExtension = 
   System.IO.Path.GetExtension(@"C:\MyApp\Images\Skyline.jpg");

Path.GetFileName(string) At times you'll have a complete path but are only interested in the file name (not the directory it exists in). The GetFileName(string) method parses the passed-in path, returning just the file name (this includes the file's extension). Example syntax:

'VB.NET... Returns "Skyline.jpg"
Dim fileExtension as String = _
   System.IO.Path.GetFileName("C:\MyApp\Images\Skyline.jpg")

// C#...  Returns "Skyline.jpg"
string fileExtension = 
   System.IO.Path.GetFileName(@"C:\MyApp\Images\Skyline.jpg");

~ and Control.ResolveUrl(string) If, from an ASP.NET page, you need to access or refer to a file that resides in a different directory, you have a number of options to refer to that file. You can use an absolute path, such as C:\Inetpub\wwwroot\DirName\FileName or /DirName/FileName, or you can use a relative path, such as ../../DirName/FileName if it's not in a subdirectory of the ASP.NET page or DirName/FileName if it is.

The problem with either of these approaches is that they are sensitive to changes in the site's layout or configuration. With absolute paths you can run into difficulties if you use different base application directories for development and production (i.e., using a virtual directory as the application root in a development server, but hosting the live version of the site in the root directory of the website). With relative paths things can go haywire if the ASP.NET page that references the file is moved to another directory.

A workaround for this is to use the ~ character in your file paths. This character references the application's root. Therefore, you can refer to the file using ~/DirName/FileName, and things will work even if the application root changes or if the ASP.NET page referencing the file is moved. Many ASP.NET server controls allow for this type of syntax. For example, in the HyperLink and Image controls you can set the NavigateUrl and ImageUrl properties using the ~. If you need to programmatically resolve a URL that starts with ~ you can use the ResolveUrl(string) method, which can be found in the Control class. Example syntax:

Returns the correct path based on the application's root. 
For example, if the application was rooted at the virtual 
directory Foo, the return value would be 
/Foo/Images/Skyline.jpg...

'VB.NET... 
Dim url as String = Page.ResolveUrl("~/Images/Skyline.jpg")

// C#... 
string url = Page.ResolveUrl(@"~/Images/Skyline.jpg");
(Thanks to Phil Winstanley for this suggestion!)

Conclusion


There are a slew of methods and properties in the .NET Framework Base Class Library that, while quite useful and versatile, are not well as well-known among the ASP.NET developer community as they ought to be. This article is an attempt in providing sets of methods and properties that most ASP.NET developers will find quite useful in real-world situations. If you have any recommendations on methods or properties that you find invaluable, but that you noticed not many folks know about, please don't hesitate to let me know.

Happy Programming!

  • By Scott Mitchell



  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article