David
David

Reputation: 16120

How to use Server.MapPath to get location outside website folder in ASP.NET

When my ASP.NET site uses documents (e.g. XML), I normally load the document as follows:

Server.MapPath("~\Documents\MyDocument.xml")

However, I would like to move the Documents folder out of the website folder so that it is now a sibling of the website folder. This will make maintaining the documents considerably easier.

However, rewriting the document load code as follows:

Server.MapPath("../../Documents/MyDocument.xml")

results in a complaint from ASP.NET that it cannot 'exit above the top directory'.

So can anyone suggest how I can relatively specify the location of a folder outside the website folder? I really don't want to specify absolute paths for the obvious deployment reasons.

Thanks

David

Upvotes: 12

Views: 60357

Answers (4)

Chris
Chris

Reputation: 27599

If you know where it is relative to your web root, you can use Server.MapPath to get the physical location of your web root, and then Path class's method to get your document path.

In rough unchecked code something like:

webRootPath = Server.MapPath("~")
docPath = Path.GetFullPath(Path.Combine(rootPath, "../Documents/MyDocument.xml"))

Sorry if I got the Syntax wrong, but the Path class should be what you are after to play with real FS paths rather than the web type paths.

The reason your method failed is that Server.MapPath takes a location on your web server and the one you gave is not valid, since it is "above" the top of the root of the server hierarchy.

Upvotes: 29

cleftheris
cleftheris

Reputation: 4839

If you need to resolve the path in either case absolute or relative (even outside the web app root folder) use this:

public static class WebExtesions
{
    public static string ResolveServerPath(this HttpContextBase context, string path) {
        bool isAbsolute = System.IO.Path.IsPathRooted(path);
        string root = context.Server.MapPath("~");
        string absolutePath = isAbsolute ? 
                                    path : 
                                    Path.GetFullPath(Path.Combine(root, path));
        return absolutePath;
    }
}

Upvotes: 2

Tadas Šukys
Tadas Šukys

Reputation: 4220

docPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\Documents\MyDocument.xml");

AppDomain.BaseDirectory returns current web application assembly directory path.

Upvotes: 6

user240141
user240141

Reputation:

If you want to specify the Location somewhere in harddrive , then its is not easily available on web environment. If files are smaller in size and quantity then you can keep it inside directory and point then using ~/path till directory.

But in some cases we used to do Request object. For more visit this link

http://msdn.microsoft.com/en-us/library/5d5940ad.aspx

Upvotes: 0

Related Questions