开发者

Converting physical path to relative one in respect of http://localhost:

I use asp.net 4 and c#.

I have this code that allow me to find the physical path for an image. As you can see I get my machine physical pagh file:///C:.

string pathRaw = HttpContext.Current开发者_StackOverflow.Request.PhysicalApplicationPath + "Statics\\Cms\\Front-End\\Images\\Raw\\";

Result:

file:///C:/......../f005aba1-e286-4d9e-b9db-e6239f636e63.jpg

But I need display this image at the Front end of my web application so I would need a result like this:

http://localhost:1108/Statics/Cms/Front-End/Images/Raw/f005aba1-e286-4d9e-b9db-e6239f636e63.jpg

How to do it?

PS: I need to convert the result of variable pathRaw.

Hope I was able to express myself unfortunately I'm not sure about terminology in this case.

Thanks for your help!


The easiest thing to do is get rid of the physical application path. If you cannot do that in your code, just strip it off the pathRaw variable. Like this:

public string GetVirtualPath( string physicalPath )
{
   if ( !physicalPath.StartsWith( HttpContext.Current.Request.PhysicalApplicationPath ) )
   {
      throw new InvalidOperationException( "Physical path is not within the application root" );
   }

   return "~/" + physicalPath.Substring( HttpContext.Current.Request.PhysicalApplicationPath.Length )
         .Replace( "\\", "/" );
}

The code first checks to see if the path is within the application root. If not, there's no way to figure out a url for the file so an exception is thrown.

The virtual path is constructed by stripping off the physical application path, convert all back-slashes to slashes and prefixing the path with "~/" to indicate it should be interpreted as relative to the application root.

After that you can convert the virtual path to a relative path for output to a browser using ResolveClientUrl(virtualPath).


Get the root of your application using Request.ApplicationPath then use the answer from this question to get a relative path.

It might need a bit of tweaking but it should allow you to do what you're after.


Left-strip your pathRaw content by the Request.ApplicationPath and construct the url using

Uri navigateUri = new Uri(System.Web.HttpContext.Current.Request.Url, relativeDocumentPath);


Make use of ApplicationPath - Gets the ASP.NET application's virtual application root path on the server.

Label1.Text = Request.ApplicationPath;
Image1.ImageUrl = Request.ApplicationPath + "/images/Image1.gif";


You can use Server.MapPath for this.

   string pathRaw = System.Web.HttpContext.Current.Server.MapPath(“somefile.jpg“);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜