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 ?

Freshblood
  • 6,285
  • 10
  • 59
  • 96

2 Answers2

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); 
Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73
  • Isn't this the reverse of what the OP asked? – GvS Jun 22 '11 at 07:56
  • Oh sorry, I rewrite the response – Tomasz Jaskuλa Jun 22 '11 at 07:59
  • 2
    thanks, its good solution but i prefer to use HttpServerUtilityBase instead of HttpServerUtility abnd HttpRequestBase instead of HttpRequestBase. working well also. – Nuri YILMAZ Oct 17 '11 at 14:54
  • +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? – Samuel Feb 23 '14 at 03:42
  • @Samuel 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. – Tomasz Jaskuλa Feb 23 '14 at 12:32
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);
dotcoder
  • 2,828
  • 10
  • 34
  • 50