C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

How to navigate to application directory resource


Posted Date: 09 Apr 2007    Resource Type: Articles    Category: .NET Framework
Author: sheetal kanugoMember Level: Gold    
Rating: 1 out of 5Points: 10



Introduction


I find myself struggling to locate a file that usually sits in the current working directory or its subdirectory. I often try to access the file directly by its file name. For example, 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.



Responses

Author: Vasudevan Deepak Kumar    17 May 2007Member Level: Diamond   Points : 0
All roads lead to Rome. Similarly you can try any of the following:

Server.MapPath
HttpRuntime.AppDomainAppPath
AppDomain.CurrentDomain.BaseDirectory


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Resource  .  Navigate  .  Directory  .  Application  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: The underlying connection was closed: A connection that was expected to be kept alive was closed
Previous Resource: [BEGINNER_INTERVIEW_AIDE] Swapping two variables without any temporary interim variable
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use