File Path and Root issues - asp.net

So I have my the path to my website code as follows:
C:/folder1/folder2/folder3/my published website code from VS2012 - on my website I get an attachment and I want to save it to the following path C:/folder4
when I try the following code: file.SaveAs(Server.MapPath("../../folder4/") + filename); it says that I am going past the root. Can someone explain to me what is going on and if and how I can solve this issue?

Server.MapPath() is used to get the path in relation to the server root. Since your trying to save it outside the server virtual directory, you could probably just hardcode the file.
file.SaveAs(#"C:/folder4/" + filename);
It might not work depending on your IIS worker pool permissions.

file.SaveAs(Server.MapPath("folder4/") + filename);
Because I cannot see your folders structure I would reccomend setting a breakpoint after Server.MapPath() to see the full URI Path to determin your next steps since it says you are past root you may have one to many "../" before your string.

As per the documentation for HttpServerUtility.MapPath:
you cannot specify a path outside of the Web application
which is exactly what you are trying to do. If you interpret "the root" to be the root folder of your application, that is even what the error message is telling you.
Either
use an absolute path or
store your data beneath the application folder
use MapPath("~/") to get the current directory and build a relative path from that (in essence, you just move the "../.." outside the call to MapPath)
I would probably recommend going with 2. as it will give less headaches wrt. permissions and multiple sites hosted on the same server.

Server.MapPath(...) tries to return a physical ("real") directory for the virtual or relative path you give it. And since a virtual directory can't be located "over" the root in that sense, what you're trying to do makes no sense. You can go from domain.com/somefolder to domain.com/, but you can't really go any farther back.
You could instead use Environment.CurrentDirectoryas the starting point to find your folder, and apart from that just use SaveAs(..) as you're already doing.

Related

Server.MapPath does not find the path on Azure

I have deployed my project to Azure. In my project I have "App_Data\Images" folder.
Now I'm trying to do the following:
String filename = GLOBAL_IMAGES_VALS.GET_FILE_PREFIX(imageType) + "-" + User.Identity.GetUserId<int>().ToString() + Path.GetExtension(image.FileName);
String origPath = Server.MapPath("~\\App_Data")+"\\Images\\" + filename;
But then upon trying:
image.SaveAs(origPath);
I get this error message:
Could not find a part of the path
'D:\home\site\wwwroot\App_Data\Images\logo-10003065.jpg'.
How can I save my file to "App_Data\Images\"?
The actual problem was that the sub-folder 'Images' did not exist. I can't remember why the publish process did not create this sub-folder, however I added it manually and then everything worked fine.
EDIT:
As others wrote here (#Spectarion). I'll put here the important remark that explain why the folder was not created:
Just for the future readers, folder won't be created if it's empty.
Folder is empty even if there are files that are not included in
project.
Just put some 'fake.txt' file into any folder you want to make sure that it will be created, and of course don't forget to add it to the project. Good luck.
Since you don't have any file in the particular folder, while publishing Web deploy ignores the empty folder.
Quick fix: Add any file to the folder before publishing will fix this issue.
if (!Directory.Exists(Server.MapPath("~/Images")))
{
Directory.CreateDirectory(Server.MapPath("~/Images"));
}
The directory might be missing in the folder. Create the directory and use it in file path
Maybe this :
System.Web.Hosting.HostingEnvironment.MapPath("~\\App_Data")+"\\Images\\" + filename )
Maybe the images folder doesn't exist and you need to create it first? Although I wouldn't recommend saving images in your app like this if it is designed for people uploading images. I would save them in Azure storage via blobs or the new Azure File storage. I would keep your app deployment files clean just related to your app and save any user generated content outside of it.
BTW, If you are using Azure Web Apps you can use the environment variable of "HOME" to always get the correct path (which should be D:\home)
string path = Environment.GetEnvironmentVariable("HOME") +
"\\site\\wwwroot\\App_Data\\images"
I assume your AppData folder is just under the wwwroot folder, which is usually the case.
Try this:
HttpContext.Current.Server.MapPath(Path.Combine("~/AppData/Images/", filename));
I just had this problem on VS15. I first followed the advice in this question in order to generate the error you've got. I'm guessing this follows in part dsb's answer, but dsb hasnt given any description of the actual process of fixing this.
I then went to https://<mywebsite>.scm.azurewebsites.net/DebugConsole to look through the directory and found that App_Data had not been published
Which was why the error was throwing. So, I then solved this by simply going to the solution explorer, right clicking App_Dataand selecting to "Publish App_Data".
However, my website was a short-term academic effort for a project - I think there is probably a lot to be said for considering Matt Watsons answer above about whether or not allowing users to upload to the deployment area is a good idea

Root path with tilde “~” does not change upper case to lower case

I have my project set up with the virtual path "/MyVirtualPath", create the virtual directory in IIS 6 (W2003) and everything works fine.
Then to work better with Google Analytics I change the virtual path "/myvirtualpath" and change all redicecciones and links to lowercase. also applies the class "lowercase route urls in aspnet mvc" and works perfectly.
The problem I had to modify the virtual directory in IIS, delete virtual path "/MyVirtualPath" and I created the new "/myvirtualpath", but in all cases I use tilde "~" or where I make a "RedirecToAction" (which should take "LowercaseRoute"), continues to maintain the virtual path "/MyVirtualPath".
For example, if I see the HTML source code in the browser, see "/MyVirtualPath/Content/Site.css" instead of "/myvirtualpath/Content/Site.css. "
Thanks
Make sure to reset IIS (run iisreset) when you make changes like this. Sometimes there are caching issues.
Try searching your metabase file directly for "MyVirtualPath" and editing it by hand. This is a dangerous and ugly technique, so take proper precautions before doing so (e.g., make sure the server is configured to automatically backup your metabase and reload it if you mess up). Though changing case is unlikely to break anything.

ASP.net relative paths not working?

This should be pretty simple but it's not working.
I have a file underneath the root of my project. I want to call it like this.
GetWorkbook("tplBud806_wRevenue.xls")
I publish the project out to the server and try to run it and the server says it can't find it.
Could not find file 'c:\windows\system32\inetsrv\tplBud806_wRevenue.xls'.
That's not the path it should be taking. It should be under E:\IIServer\rootwww\reports\tplBud806_wRevenue.xls.
I thought relative paths were supposed to start from the path that the project was running in. I've also tried.
GetWorkbook("/tplBud806_wRevenue.xls")
GetWorkbook("\tplBud806_wRevenue.xls")
GetWorkbook("~/tplBud806_wRevenue.xls")
GetWorkbook("~\tplBud806_wRevenue.xls")
Is there some setting I'm missing? It's got to be something simple...
GetWorkBook(Server.MapPath("tplBud806_wRevenue.xls"));
GetWorkbook is not an ASP.NET function, and it likely defaults to the folder that the process calling it was started from. The process in this case is an IIS process and probably started in that folder.
Server.MapPath?
Your application is running in an AppDomain loaded by the w3wp.exe located in the directory in your error. Which means that trying to look for any file will start in that directory. You should use Page.MapPath, as mentioned by others. It tells the application to start looking in the folder your aspx is in.
GetWorkBook(Server.MapPath("~/tplBud806_wRevenue.xls")); If the .XLS file is at the root of your project.
You can use also use ~ in conjuction with ResolveURL() to access an URL in your site. So ~ will be replaced by the root URL of your project
Example:
ResolveURL("~\tplBud806_wRevenue.xls")
will be transformed to
http://myproject.url/website/tplBud806_wRevenue.xls
If you need disk access, like in your example, use Server.MapPath
Look at this SO post to learn more about Server.MapPath

ImageUrl trying to display an image outside of project root

I am working with two different web sites in asp.net. In the first project i upload some images to a specific folder under the project root and save just the filename in the database, now i am trying to display this images at some page of the second project I know the filename from the database and the image folder as absolute pat but I have not been able to display the image, even thought when looking in firebug the image src is correct src="D:/MyFolder/image.jpg" the image does not display, probably because it is not pointing in the right directory.
I have also tried using Server.MapPath and then my D location but still no success.
I am sure someone has faced the same situation before and was really hoping to get some hint to manage this.
Thank you in advance
I found my solution, strange but i didn't catch it before. Uploaded pictures under a project can always be accessed using the url of the project http://www.yourwebsite.com/images/photo.png now in the second project you can use reference the images using this url and concatenating the file name which i store on database. I think this is the best solution and without changing the code access security which i think can bring other problems with it. Anyway thank you guys.
If you want to display the image that is not in your project (I mean it is present in some other project or some other drive) just create the virtual directory in IIS
Go to "Run", type inetmgr
Right click on your project and add virtual directory
Give alias name and path so that it acts like folder in your project
I don't think you can serve files outside of your application path by default. It's called Code Access Security. You can read up on it here:
http://msdn.microsoft.com/en-us/library/930b76w0.aspx
You can fix this by changing your trust level to High in your web.config:
http://msdn.microsoft.com/en-us/library/tkscy493.aspx
I wouldn't recommend doing this for any site that is externally accessible. In fact, depending on how/where you're hosting your application, this option may be restricted.
You can only "link" to files that exist relative to the same project or are hosted on another site via an absolute URL.
If you want to service files outside the application/website (on disk or in a database) you will need to build a mechanism that gets the file and binary writes it to the browser, setting the MIME type etc. This is best done using an HttpHandler.

asp includes with absolute path

is there anyway to do a #include with a file listed as an absolute path?
i am trying to include files from other websites (outsite the root of the sight that wants to include it)
any other suggestions?
You can only include files from your server, these may technically be outside your website if the Allow Parent Paths option is enabled or if you can use a virtual include to point to another virtual directory on your server.
There is no way to include files from websites outside of your server or sites on your server that your application does not have permissions to access.
Another way to go is to create a directory below the root folder of your website, then making that folder a symbolic link to the folder where the file you want to include is located. Now there is no way to create symbolic links in Windows out of the box, you need Microsoft Sysinternals Junction for that.
<!--#include file="c:\boot.ini"-->
There is a setting in IIS for allowing includes to parent paths, check that if the above doesn't work.
You can do it, using XMLHTTP and the VBscript Execute statement.
I wouldn't recommend it though as it creates substantial security risks.
A few links to get you started:
https://web.archive.org/web/20211020135215/https://www.4guysfromrolla.com/webtech/042602-1.shtml
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vsstmexecute.asp
https://web.archive.org/web/20210927184623/http://www.4guysfromrolla.com/webtech/110100-1.shtml
It is a very high security risk, because someone can inject code into your app. Take your precautions.
One tip: the page you need to load from another server needs to have an extension different from .asp because if not the other server is going to send it already executed. It seems clear but I forgot it the first time!

Resources