Introduction
From time to time, I find myself struggling to locate a file
that usually sits in the current working directory or
its subdirectory. Absent-minded, I often try to access the file directly
by its file name. For example, I create a StreamReader
to read a file named
Test.txt as such:
StreamReader sr=new StreamReader("Test.txt");
Of course, my ASP.NET application goes out to search C:\WINNT\system32\
and report back an error with an "alarming" message:
"Could not find file 'C:\WINNT\system32\Test.txt".
Sure. Sure. But this made me think and do some research on
the means and methods regarding the common problem.
So should you correctly locate the path of a specific file or other
application-related path information?
The various path-related properties of the Request Object
Fortunately, The ASP.NET
Request object is equipped with a number of properties with regards
to this.
They are:
ApplicationPath
|
Gets ASP.NET application's virtual application root path on the server
|
CurrentExecutionFilePath
|
Gets the virtual path of the current request.
|
FilePath
|
Path
|
PathInfo
|
PhysicalApplicationPath
|
Gets the physical file system path of the currently executing server application's root directory
|
PhysicalPath
|
Gets the physical file system path corresponding to the requested URL
|
RawUrl
|
Gets the raw URL of the current request
|
Url
|
Gets information about the URL of the current request
|
However, these properties along with their definitions
are a bit confusing. So I wrote some simple code to see exactly which path those
properties lead to.
For example, I have a website called ASPNETC and it is a subfolder
of my website root folder (C:\webs), and I get the following output:
ApplicationPath: "/"
CurrentExecutionFilePath: /aspnetc/testpath.aspx
FilePath: /aspnetc/testpath.aspx
Path: /aspnetc/testpath.aspx
PathInfo:
PhysicalApplicationPath: C:\webs\
PhysicalPath: C:\webs\aspnetc\testpath.aspx
RawUrl: /aspnetc/testpath.aspx
Of the above, CurrentExecutionFilePath, FilePath,
Path,
RawUrl return
exactly the same virtual path, while PathInfo comes back blank (which is
not very useful). However RawUrl will also return the trailing
QueryString if the url has any. PhysicalApplcationPath and
PhysicalPath
are self-evident. Somehow I wish there were something like
PhysicalDirectory that returns the dirctory information about the current
request.
The ApplicationPath has got a lot of bad attention, since it returns either
"/" if the application is in the root folder or "/xxx" without a trailing slash
if it is in a virtual directory. So if you move your website around, and if
folder hierarchy is not consistent,
you are in trouble (be sure to track if there is a trailing "/" when using the
ApplicationPath).
The famous "~" and Page.ResolveUrl
Of course, it is a hassle to remember all the various properties
of the Request object especially with the problems associated with the ApplicationPath property.
So here comes a handy trick, the tilde
"~". It denotes the root directory of the web application. It can be used
in many server controls, such as Image controls, where you can
set the ImageUrl property with a leading "~" to indicate the path of
the image, as such:
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="~/images/image1.jpg"/>
Preceding your url with a "~" bypasses the problem that may arise when
you have to move an application to different servers with
different root settings.
The very useful Page method ResolveUrl also addresses the same
problem.
For example, if your application is located in a virtual directory "/SomeDir"
Page.ResolveUrl("~/images/image1.jpg") will return "/Somedir/images/image1.jpg"
However if it sits in the root directory:
Page.ResolveUrl("~/images/image1.jpg") will simply return "/images/image1.jpg"
Server.MapPath
All the above concerns are more or less with the relative or virtual path.
However, a lot of times it is necessary to retrieve the physical path
of a file or a directory and my favorite method for this task is
Server.MapPath, the age-old method that I have been
using since my ASP years (I still write a lot of ASP pages.)
Given a relative or virtual path of a directory or file, Server.MapPath
can be used to obtain its physical path. For example:
Server.MapPath("testdir/testFile.aspx")
or
Server.MapPath("testdir")
The neat thing about Server.MapPath is that it can return the
root directory of an application, as the following:
Server.MapPath("/")
Or it maps to the physical path of the current working directory, which
is what I often need.
Server.MapPath(".")
Or it can map to the parent directory of current working directory.
Server.MapPath("..")
The System.IO.Path Object
Talking about Paths, the .NET Path object is
also very helpful in terms of extracting various path and file
information.
It has a slew of static methods, most notably:
-
GetExtension
-
GetFileName
-
GetFileNameWithoutExtension
Here a quick example:
String strPath = @"c:\testdir\testfile.txt";
//returns c:/testdir
temp = path.GetDirectoryName(strPath)
//returns testfile.txt
temp = Path.GetFileName(strPath);
//returns .txt
temp = Path.GetExtension(strPath);
//returns testfile
temp = Path.GetFileNameWithoutExtension(strPath);
Another neat method of the Path object is Path.Combine
that combines two paths together. So instead of concatenating two path strings
together, we can use Path.Combine to get a complete path, as the
following:
//Returns C:\testdir\images\image1.jpg
Path.Combine(@"C:\testdir", @"Images\image1.jpg");
Summary:
We have talked about how to retrieve the various path / url information
of a file/directory/application, be it a virtual path, relative path or
physical path. ASP.NET has a number of properties and methods for
this task.
-
The Request object has a number of properties
such as ApplicationPath, CurrentExecutionFilePath,
PhysicalApplicationPath.
However, these properties can sometimes be too confusing. Also, the
inconsistency of the ApplicationPath property (with or without trailing
"/") can cause frustration.
In ASP.NET, developers often use the tilde "~" to denote the root-relative path of a web application, or
using the Page.ResolveUrl to obtain the same information.
-
In terms of
retrieve the physical path of a file or a directory (current working
directory, parent directory or root directory), I love to use
the old-fashioned Server.MapPath.
-
The Path object in System.IO namespace
comes handy for retrieving such information as file extension,
file name or the full path of a file.
References
Little Known, Invaluable Methods and Properties
in the .NET Framework Base
Class Library : Working with File Paths
Making sense of ASP.Net Paths
Top Articles in this category
JavaScript with ASP.NET 2.0 Pages - Part 1
ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and method of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.
ASP.NET ComboBox
The ASP.NET ComboBox is an attempt to try and enhance some of the features of the Normal ASP.NET DropDownList.
Upload multiple files using the HtmlInputFile control
In this article, Haissam Abdul Malak will explain how to upload multiple files using several file upload controls. This article will demonstrates how to create a webform with three HtmlInputFile controls which will allow the user to upload three files at a time.
JavaScript with ASP.NET 2.0 Pages - Part 2
ASP.NET provides a number of ways of working with client-side script. This article explores the usage and drawbacks of ASP.NET script callbacks, and briefly presents a bird's view of ASP.NET AJAX.
Using WebParts in ASP.Net 2.0
This article describes various aspects of using webparts in asp.net 2.0.
|
|
Please login to rate or to leave a comment.