Converting the physical path to relative with respect to http: // localhost:

I am using asp.net 4 and c #.

I have this code that allows me to find the physical path for the image. As you can see, I get the file of the physical file machine: /// 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 to display this image on the front of my web application, so I need the result:

 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 the variable pathRaw .

I hope that I was able to express myself, unfortunately, I am not sure of the terminology in this case.

Thanks for your help!

+6
source share
5 answers

The easiest way to do this is to get rid of the physical application path. If you cannot do this in your code, just split it with 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 in the root of the application. If not, there is no way to calculate the URL for the file, so an exception is thrown.

A virtual path is created by removing the physical path of the application, converting all backslashes to slashes, and prefixing the path with "~/" to indicate that it should be interpreted as relative to the root of the application.

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

+11
source

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

It may take a little tweaking, but it should allow you to do what you need.

+1
source

Put your pathRaw content in the Request.ApplicationPath field and create the url using

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

You can use Server.MapPath for this.

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

Use ApplicationPath - Gets the root path of the ASP.NET application virtual application on the server.

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

Source: https://habr.com/ru/post/890040/


All Articles