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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With