How to get server path of physical path ?
Asked Answered
C

2

9

I want to convert this physical path "C:\bla\bla\Content\Upload\image.jpg" to server path like "/Content/Upload/image.jpg".

How can i do that ?

Croon answered 22/6, 2011 at 7:34 Comment(2)
Where? In the client-side or server-side?Sexton
possible duplicate of ASP.NET absolute path back to web-relative pathDelphinium
W
11

you can use something like that :

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

and you call

Server.RelativePath(path, Request); 
Wofford answered 22/6, 2011 at 7:45 Comment(5)
Isn't this the reverse of what the OP asked?Calley
Oh sorry, I rewrite the responseThessalonians
thanks, its good solution but i prefer to use HttpServerUtilityBase instead of HttpServerUtility abnd HttpRequestBase instead of HttpRequestBase. working well also.Idun
+1 even if I think it's not a good idea to add an extension to a class where at least one property or method are used in the helper method. In this case, the RelativePath could be at a better place in a helper class like PathResolver. What do you think?Zoophilia
@Zoophilia Yes, it's just a quick sample but actually you could create a helper class that fits your needs called like you said a PathResolver.Thessalonians
M
2

You can do the following to get the relative path.

String filePath = @"C:\bla\bla\Content\Upload\image.jpg";

String serverPath = Request.PhysicalPath;
String relativePath = filePath.Substring(serverPath.Length, filePath.Length - serverPath.Length);
Minimize answered 22/6, 2011 at 8:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.