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

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
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

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


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



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES