Your full service technology partner! 
-Collapse +Expand
Search C# Group:

-Collapse +Expand C# To/From
-Collapse +Expand C# Study Test
-Collapse +Expand C# Store

Prestwood eMagazine

June Edition
Subscribe now! It's Free!
Enter your email:

   ► KBProgrammingC#WebForms Cod...   Print This     
  From the February 2016 Issue of Prestwood eMag
C# WebForms Coding Tasks:
Getting Website Root Directory in C# ASP.NET
Posted 12 years ago on 12/12/2008 and updated 10/24/2009
C# Code Snippet:
 A flashcard from our C# Flashcards Library
 A code snippet from our C# Code Snippets Page


This code shows how to ask the webserver where the site's root directory is, and how to convert a relative path (like /Uploads) to the full filesystem path.  This will work across environments (i.e. Development/QA/Production).

Syntax Example:
string ServerPath2 = Server.MapPath(@"~/");

This gives the full path to the webserver's root directory. 


"C:\\Documents and Settings\\All Users\\Documents\\Visual Studio 2008\\WebSites\\MySite\\"

string ServerPath2 = Server.MapPath(@"~/Uploads");

This gives the full path to the Uploads subdirectory - even if it is a virtual directory in another location! 

...even if it is not a browsable web directory (such as APP_CODE or APP_DATA).

This is quite useful when creating logs or reading config files; but my number one use is when using FileUpload objects on a web page.  Look how easy it is to store an uploaded file in the /uploads subdirectory!

string ServerPath = Server.MapPath(@"~/Uploads");
if (FileUpload1.HasFile)
String ThisFile = string.Format(@"{0}\{1}", ServerPath, FileUpload1.FileName);

Piece of cake, right?


Share a thought or comment...
Comment 1 of 1

Getting Website Root Directory will be a good idea for all of us. We can get help in assignments with the help of this dictionary . I am going to share this blog with the readers and readers will understand it.

Posted 19 months ago
Write a Comment...
Sign in...

If you are a member, Sign In. Or, you can Create a Free account now.

Anonymous Post (text-only, no HTML):

Enter your name and security key.

Your Name:
Security key = P145A1
Enter key:
Code Contributed By Bryan Valencia:

Bryan Valencia is the author of millions of lines of code and writes for PrestwoodBoards and Visual Studio Journey on-line magazines.

Visit Profile

 KB Article #101679 Counter
Since 12/12/2008
Go ahead!   Use Us! Call: 916-726-5675  Or visit our new sales site:

©1995-2020 Prestwood IT Solutions.   [Security & Privacy]