Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 487
David Avatar asked Aug 06 '10 08:08

David


1 Answers

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;
    }
}
like image 139
cleftheris Avatar answered Nov 16 '22 03:11

cleftheris