Home » Questions » Computers [ Ask a new question ]

Absolute path back to web-relative path

Absolute path back to web-relative path

If I have managed to locate and verify the existence of a file using Server.MapPath and I now want to send the user directly to that file, what is the fastest way to convert that absolute path back into a relative web path?

Asked by: Guest | Views: 295
Total answers/comments: 4
Guest [Entry]

"Perhaps this might work:

String RelativePath = AbsolutePath.Replace(Request.ServerVariables[""APPL_PHYSICAL_PATH""], String.Empty);

I'm using c# but could be adapted to vb."
Guest [Entry]

"Wouldn't it be nice to have Server.RelativePath(path)?

well, you just need to extend it ;-)

public static class ExtensionMethods
{
public static string RelativePath(this HttpServerUtility srv, string path, HttpRequest context)
{
return path.Replace(context.ServerVariables[""APPL_PHYSICAL_PATH""], ""~/"").Replace(@""\"", ""/"");
}
}

With this you can simply call

Server.RelativePath(path, Request);"
Guest [Entry]

"I know this is old but I needed to account for virtual directories (per @Costo's comment). This seems to help:

static string RelativeFromAbsolutePath(string path)
{
if(HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
var applicationPath = request.PhysicalApplicationPath;
var virtualDir = request.ApplicationPath;
virtualDir = virtualDir == ""/"" ? virtualDir : (virtualDir + ""/"");
return path.Replace(applicationPath, virtualDir).Replace(@""\"", ""/"");
}

throw new InvalidOperationException(""We can only map an absolute back to a relative path if an HttpContext is available."");
}"
Guest [Entry]

"I like the idea from Canoas. Unfortunately I had not ""HttpContext.Current.Request"" available (BundleConfig.cs).

I changed the methode like this:

public static string RelativePath(this HttpServerUtility srv, string path)
{
return path.Replace(HttpContext.Current.Server.MapPath(""~/""), ""~/"").Replace(@""\"", ""/"");
}"