Htmlfile access is denied when using Server.MapPath - c#

I have been using Server.MapPath("page.aspx") for quite a long time, but it is just now that I faced this problem.
Basically here is my code
Session.Clear();
ShowLoggedOffControl(); //A function that setup bunch of controls visibility
OnUserLoggedOut(new EventArgs());
Response.Redirect(Server.MapPath("~/Default.aspx"));
The error would be htmlfile:access is denied at javascript execution. However when I removed Server.MapPath so that it became like this Response.Redirect("~/Default.aspx");, things work normally.
What did I do wrong? Why, how and when can I use Server.MapPath?
Thanks.

Server.MapPath maps the specified relative or virtual path to the corresponding physical directory on the server. So in your example it would end up redirecting to something like this:
c:\Projects\MyWebsite\Default.aspx
which is probably not what you want.
Response.Redirect on the other hand will resolve the '~' to the relative path root for you and resolve to something like this:
/MyVirtualDirectory/Default.aspx
As for when you would want to use Server.MapPath, you would use it if you wanted to actually find the file on the server and do something such as:
var lines = System.IO.File.ReadAllLines(Server.MapPath("~/MyTextFile.txt"));
// Do something here with values found

Server.MapPath gets the physical path to the file on the hard disk, whereas Response.Redirect expects a URL.
If for some reason you need to get the full URL, you can use this:
String.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));

Related

unable to load a local resource OR virtual path error

Situation
I have two applications that both read and save images / documents to one specific folder. Example if the user uploads their image in one program, a user of program B is supposed to view and even edit that image.
What I have done
In one of my application I have created a setting in settings for the string of my path. So to save an image path I call
path = System.IO.Path.Combine(Properties.Settings.Default.imagePath, Fimage);
this works fine.
However, my issue is when I try to view the image in my edit view.
Controller
ViewBag.imagePath = Properties.Settings.Default.imagePath;
View
<img src="#ViewBag.imagePath/#Url.Content(#Model.image)" alt="Image" style="height: 255px; " />
Problem
The problem is upon attempting to view the image I get the error, Not allowed to load local resource: I have full access to the folder and when I attempt to browse to the file in the error message the picture is displayed. I was advised from other questions to use, server.MapPath however when I do Server.MapPath(Properties.Settings.Default.imagePath); I get the error physical path received, expected virtual path.
This viewbag holds the entire string of folder my files are stored with the EVERYONE user having full access. So i'm really unsure of why it's making a fuse.
P.S I cant say something like "~/content/images" because the path to that file is in an entirely different application, I think I need to give it the entire location.
Any assistance will be appreciated.
Gratitude
Looks like your defaultImage variable holds a physical path, which will work for saving the image since the API requires a path in the form e.g. c:\website\images\.... but for viewing, you need the VirtualPath, something of the form http://mycoolsite/images/image.jpg and this is what the error is telling you.
Your Controller; therefore, should return something like
ViewBag.imagePath = Properties.Settings.Default.imagePath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
In order to get the Relative Path. See this other related question.
EDIT I just saw your "PS..."
If that's the case, then you need to pass the full URL to the other application: (e.g. http://someothersite.com/images/image.jpg).

Use of ServerMapPath in C#

In a block of code, i have the following line:
CsvFile= #"D:\Web\Preps\en\csr\downloadcenter\ClickCounter.csv";
I try to use Server.MapPath instead:
CsvFile = Server.MapPath(#"../en/csr/downloadcenter/ClickCounter.csv");
(the file from where i write this line is located at the same level as "csr" but in a different folder)
I don't have any errors appearing since i'm not using visual studio. Does anyone know what i'm doing wrong ? Thanks for your help
You said that your file is in a folder at the same level of the csr folder, something like
D:\Web\Preps\en\YourFolder, am I right ? Then, your path is not correct.
Try this :
CsvFile = Server.MapPath(#"../csr/downloadcenter/ClickCounter.csv");
or this :
CsvFile = Server.MapPath(#"../../en/csr/downloadcenter/ClickCounter.csv");
The reason your path is not correct is because the way you're using it, you're trying to access
D:\Web\Preps\en\en\csr\downloadcenter\ClickCounter.csv. There is an unneeded en
Assuming that the directory you are after is "under" your web site directory then:
Server.MapPath("~/")
Will take you to the root of your website, from there navigate to somewhere else i.e.
Server.MapPath("~/en/csr/downloadcenter/ClickCounter.csv")
If you don't want to get to the root of your site and it's located somewhere else on the server, then I have misunderstood the question. In this instance you will need to ensure the site has permissions to the respective directory.

How to get image files in c# using relative path?

I've checked this thread How to get files in a relative path in C#, the directory is in IDE, which is not correct for me. I have a website application, needs to get image files from the same level folder img. I can use following code to get them:
DirectoryInfo path=new DirectoryInfo(#"c:\WebsiteSolution\wwwroot\Chat\img");
FileInfo[] images = path.GetFiles("*");
But I want to use something like .\img to replace the parameter in the first line code, is that possible?
Call the Server.MapPath utility to get the relative path.
DirectoryInfo path = Server.MapPath("~\Chat\img");
For ASP.Net use MapPath - http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx.
Also if you just need to construct path for rendering a page just /Chat/img/My.gif is enough.
You need to find an anchor - something like Application.ExecutablePath - and then use that anchor with Path.Combine() to reach your image directory.
If your Application.ExecutablePath were: #"c:\WebSiteSolution\wwwroot\chat\code", then you could use string imgPath = Path.Combine(Application.ExecutablePath, #"..\img");
If you have a hard time finding a good anchor, there's a bunch to consider. You can get the path of the executing assembly via Assembly.GetExecutingAssembly().Location

Getting the physical path

I have to fetch all the files from a folder and i am using the function GetFiles() like
string[] dirImages = Directory.GetFiles(strPathYearImages + intYear , "*.png");
where strPathYearImages="Images\Holiday\2010\"
but when i write the whole path like
string[] dirImages = Directory.GetFiles(#"E:\IWP\Images\Holiday\"+ intYear , "*.png");
i get the required result.
How to solve this problem? I dont want to use the whole path.
Help me out.
Regards,
Jigar <3
The documentation for GetFiles() says:
The path parameter is permitted to
specify relative or absolute path
information. Relative path information
is interpreted as relative to the
current working directory
So you would want to make sure the current working directory is set correctly before trying to use the relative paths (eg to E:\IWP):
GetCurrentDirectory
SetCurrentDirectory
Use Application.StartupPath to get the location where the executable is running. From there you need to know where the images directory is relative to that directory. The only other option is the absolute path. How else would it know where to look?
You can also try using System.IO.Path methods to help - especially for combining path strings, plus it also gives you the location of special folders like My Documents, AppData, and the desktop.
Maybe it's because you are running it from VS inside. Your executable is in ProjectName\bin\Debug, therefore it looks for ProjectName\bin\Debug\Images, which obviously does not exists.
The problem is the first snippet tries to get the images under current path. So you could tell the images path relative to your current path.
Hey all, i got the answer to my question.
I just had to write
string[] dirImages = HttpContext.Current.Server.MapPath(strPathImages + intYear , "*.png");
Hope that it is helpful to all...

IE webbrowsercontrol losing .. in file path of URL

When a IE browser control is embedded in a winform and the link on a page contains a relative file path the URL coming into the callback for the navigate event seems to lose "file:///../../dir/file.htm" and becomes "file:///dir/file.htm"
private void OnNavigating(object sender, WebBrowserNavigatingEventArgs e)
{
// looking at e.Url to see what happens
}
Has anyone seen similar problems? Any suggestions?
I think your URL is incorrect. If you want a relative path, just specify a relative path, such as ../../dir/file.htm. If your URL starts with a protocol specifier, then it's an absolute URL, where a .. at the start is superfluous, since you're already starting at the root of the file system.
file:///../../dir/file.htm is not a valid url. By definition the URI cannot be relative.
(Hence the 'U' in URI/URL)
I agree with other suggestions here: don't use file:///, just specify the relative path directly.

Categories