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

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.

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“);

Related

Is there a method to manage relative paths in C#? [duplicate]

I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

Relative, Direct URL

I have a little question about my URL .
I use a tree view on my asp page that's why I use this getcurrentdirectory .
//DirectoryInfo di = new DirectoryInfo("~" + GetTheCurrentDirectory
(selectedNodeValue));
~ = C://Inetpub//WwwRoot//
GetTheCurrentDirectory = Projects//Folder1//
So for the moment it's fine because i Can load all the files for a folder.
After I try to download the files when you click on it .
protected void Page_Load(object sender, EventArgs e)
{
string path = Request["path"].ToString();
string filename = Request["file"].ToString();
fileDownload(filename, Server.MapPath("~\\" + path + filename));
}
So I can retrieve the Path wich is the current directory . The method I use in my other page.
In the server.MapPatch should I put ~ also ? Because when I do that is works localy, but when I put this on my server , the downloading part doesn't work so I suppose this is a URL issue, I can't debug so I am really lost about this !
I changed some things :
DirectoryInfo di = new DirectoryInfo(GetTheCurrentDirectory(selectedNodeValue));
So its returns the same thing .
So now in the server.MapPath the path equal something like Projects//Folder 1//
It works locally, but still not on the server ...
Try this:
fileDownload(filename, Server.MapPath("~/" + path + filename));
And also, as a best practice, don't use + to concatenate strings. You should use string.format, so I would write the above line as follows:
fileDownload(filename, Server.MapPath(string.format("~/{0}{1}", path, filename)));
Just to help you understand your problem better, Server.MapPath will return you a physical file path on the server which corresponds to the virtual path on the web server. i.e. it converts "http://website.com/img.jpg" to something like "C:\mywebsite\img.jpg"
UPDATE:
Make sure the folder you're trying to save the file to, is not read-only and you have permissions to create files in the folder.

File.Exists using the wrong root path?

In my c# class I wrote I have a photo property that returns the photo source if the image exists (nothing or default image otherwise). In my code I use:
public string Photo
{
get
{
string source = "~/images/recipes/" + id + ".jpg";
if (File.Exists(source))
return "~/images/recipes/" + id + ".jpg";
else
return "";
}
}
If I get the FileInfo() information for this image I see that I tries to find this image in the following directory: C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\~\images\recipes
Of course the image is not located in that directory and File.Exists is returning me the wrong value. But how can I fix this?
Try this:
if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))
You need to map the relative path back to a physical path:
string source = HttpContext.Current.Server.MapPath("~/images/recipes/" + id + ".jpg");
You'll have to use:
Server.MapPath(source)
As you can not be 100% sure where the code will be running from, ie. it will be different in development and on a production server. Also are you sure ~/ works in windows? Wont that just be interpreted as a directory named ~? Unless thats what you want.

Relative path to absolute path in C#?

I have xml files that contain href file paths to images (e.g. "....\images\image.jpg"). The hrefs contain relative paths. Now, I need to extract the hrefs to the images and turn them into absolute paths in the file system.
I know about the GetFullPath method, but I tried it and it only seems to work from the CurrentDirectory set, which appears to be C: so I don't see how I could use that. And still, I have the absolute path of the file containing the hrefs, and the href relative paths, so since it is a simple task for me to count back the number of "....\" parts based on the absolute path of the containing file, it seems there must be a way to do this programmatically as well.
I'm hoping there's some simple method I just don't know about! Any ideas?
string exactPath = Path.GetFullPath(yourRelativePath);
works
Assuming you know the real directory the XML file lives in use Path.Combine, e.g.
var absolute_path = Path.Combine(directoryXmlLivesIn, "..\images\image.jpg");
If you want to get back the full path with any ..'s collapsed then you can use:
Path.GetFullPath((new Uri(absolute_path)).LocalPath);
This worked.
var s = Path.Combine(#"C:\some\location", #"..\other\file.txt");
s = Path.GetFullPath(s);
It`s best way for convert the Relative path to the absolute path!
string absolutePath = System.IO.Path.GetFullPath(relativePath);
You can use Path.Combine with the "base" path, then GetFullPath on the results.
string absPathContainingHrefs = GetAbsolutePath(); // Get the "base" path
string fullPath = Path.Combine(absPathContainingHrefs, #"..\..\images\image.jpg");
fullPath = Path.GetFullPath(fullPath); // Will turn the above into a proper abs path
Have you tried Server.MapPath method. Here is an example
string relative_path = "/Content/img/Upload/Reports/59/44A0446_59-1.jpg";
string absolute_path = Server.MapPath(relative_path);
//will be c:\users\.....\Content\img\Upload\Reports\59\44A0446_59-1.jpg
This worked for me.
//used in an ASP.NET MVC app
private const string BatchFilePath = "/MyBatchFileDirectory/Mybatchfiles.bat";
var batchFile = HttpContext.Current.Server.MapPath(BatchFilePath);
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx

Silverlight file path separator issue

I find when reading from a local file from Silverlight, we have to use special path separator "/" other than normal path separator "\" or else Silverlight can not get related local file, for example we need to write as c:/test/abc.wmv, other than write as c:\test\abc.wmv.
Two more questions,
Any simple solution to use normal file separator?
C# File/FileInfo class will use normal path separator to represent a file name (full path name), how to change all the normal path separator into this special path separator so that Silverlight could recognize?
I am using VSTS 2008 + C# + .Net 2.0.
thanks in advance,
George
You could use an Extension Method:
public string ToSilverlightPath(this string s)
{
return s.Replace("\\", "/");
}
or
public string ToSilverlightPath(this Path p)
{
return p.GetFullPath().Replace("\\", "/");
}
Edit:
After thinking about it some more Silverlight probably works with URIs'.
That is, all paths in Silverlight are URIs'.
So instead of using Path you should probably use Uri, like:
Uri mySilverlightPath = new Uri(myPathString);
or
Uri mySilverlightPath = new Uri(myPath.GetFullPath());
Not sure about this though but I guess it would make sense.

Categories