How to display html file from local folder inside an iframe? - c#

I try to display html file inside an iframe.
The html file is located inside a local folder on my server, with the relevant permissions (for example: c:\temp).
I tried:
iframe = document.createElement("iframe");
iframe.src = "file:///c:\temp\a.html";
iframe.style.display = "block";
document.body.appendChild(iframe);
But the content is not displayed inside the iframe.
another solution I tried is to use ajax to display the html inside a div:
$("#DIV").html( *READ HTML TEXT FROM FILE *)
But the problem here is that I have pictures and css file included inside the html page, and they can't be displayed because the current location is my web site (they are included in c:\temp folder with the html).
Does anyone have an idea how can I display html page with images inside an iframe?

The problem is that the browser sees that file:///c:\temp\a.html as a file local to the browser, so it points to the C: drive of the visitor.
You can set up that local folder to be a Virtual Directory of your website (in IIS) and refer to the file using the correct web-path (http://...). That way you don't move the folder but it is still available through the webserver.

Assuming it works properly when you load the html file from the root instead of temp (thus, ruling out everything except an issue with the file location), you can load a file relative to your website as long as you have access. It does require understanding your path(s) - both local and server, if applicable. For instance, I have a folder called ‘temp’ on a hosted server that is a peer to my website.
Using Request.PhysicalApplicationPath, I find that my site is located here on my host: "c:\inetpub\wwwroot\mydomain.com\index.htm”. Therefore my temp folder & file must be at “c:\inetpub\wwwroot\temp\myfile.txt" (again, temp is a peer to my site).
Crude Example:
string _filePath, _uriServerName = "";
_filePath = Request.PhysicalApplicationPath;
_uriServerName = Request.ServerVariables["SERVER_NAME"].ToLower();
if (_uriServerName != "localhost")
{
int rootPos = _filePath.IndexOf("wwwroot"); //get position wwwroot
_filePath = _filePath.Substring(0, rootPos) + "temp\\myfile.txt";
}
I use the above for loading files outside web site. For that, it works well. However, an iframe may present some other challenges. I don't believe this should present any cross-domain issues, but I'm not perfectly sure.

Related

Visual Studio 2022 C# ASP.NET Webforms with service reference text files not found on server (HTTP Error 404.0)

I am currently trying to create a web service application using Visual Studio 2022 ASP.NET Webforms application with a service reference. The goal is to take in information and store it as a text file on the local machine within the project folder so it is accessible by the web service on my local server.
I have successfully created the text files and can access them on my local machine, but when I navigate to the text file on my local server tree I get an HTTP Error 404.0 which is shown below. I need any user who accesses my server to be able to access the saved text files. I have tried to change security privileges on the folder and in my web.config file, but have not had any luck. I would appreciate any suggestions someone may have.
Here is my code for where I save the information as a text file.
// Randomly generate string for text file name
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var textFile = new char[4];
var random = new Random();
for (int i = 0; i < textFile.Length; i++)
{
textFile[i] = chars[random.Next(chars.Length)];
}
eventFile = "\\";
eventFile += new String(textFile);
eventFile += ".txt";
folderPath = Server.MapPath("~/Events");
File.WriteAllText(folderPath + eventFile, fullEventDetails);
Both my URL and local file path are the following:
URL https://localhost:44399/sx1l.txt
Path Name \\Mac\Home\Desktop\Homework3\Homework3\sx1l.txt
Ok, so you have to keep in mind how file mapping works with IIS.
Your code behind:
that is plane jane .net code. For the most part, any code, any file operations using full qualified windows path names. It like writing desktop software. For the most part, that means code behind can grab/use/look at any file on your computer.
However, in practice when you use a full blown web server running ISS (which you not really doing during development with VS and IIS express)? Often, for reasons of security, then ONLY files in the wwwroot folder is given permissions to the web server.
However, you working on your development computer - you are in a effect a super user, and you (and more important) your code thus as a result can read/write and grab and use ANY file on your computer.
So, keep above VERY clear in your mind:
Code behind = plane jane windows file operations.
Then we have requests from the web side of things (from a web page, or a URL you type into the web browser.
In that case, files are ONLY EVER mapped to the root of your project, and then sub folders.
So, you could up-load a file, and then with code behind save the file to ANY location on your computer.
However, web based file (urls) are ONLY ever mapped though the web site.
So, in effect, you have to consider your VS web project the root folder. And if you published to a real web server, that would be the case.
So, if you have the project folder, you can add a sub folder to that project.
Say, we add a folder called UpLoadFiles. (and make sure you use VS to add that folder). So we right click on the project and choose add->
So, you right click on the base project and add, like this:
So, that will simple create a sub folder in your project, you see it like this:
So, the folder MUST be in the root, or at the very least start in the root or base folder your project is.
So, for above, then with UpLoadFiles, then any WEB based path name (url) will be this:
https://localhost:44399/UpLoadFiles/sx1l.txt
(assuming we put the file in folder UpLoadFiles).
But, if you want to write code to touch/use/read/save and work with that file?
You need to translate the above url into that plane jane windows path name. (for ANY code behind).
So, if I want to in code read that file name?
Then I would use Server.MapPath() to translate this url.
say somthing like this:
string strFileName = "sx1l.txt";
string strFolderName = "UpLoadFiles"
string strInternaleFileName = server.MapPath(#"~/" + strFolderNme + #"/" + sx1l.txt";
// ok, so now we have the plane jane windows file name. It will resolve to something like say this:
C:\Users\AlbertKallal\source\repos\MyCalendar\UpLoadFiles\sx1l.txt
I mean I don't really care, but that web server code could be running on some server and that path name could be even more ugly then above - but me the developer don't care.
but, from a web browser and web server point of view (URL), then above would look like this:
https://localhost:44392/UpLoadFiles/sx1l.txt
And in markup, I could drop in say a hyper link such as:
UpLoadFiles/sx1l.txt
So, keep CRYSTAL clear in your mind with working with path names.
Web based URL, or markup = relative path name, ONLY root or sub folders allowed
code behind: ALWAYS will use a plane jane full windows standard file and path.
But, what about the case where you have big huge network attached storage computer - say will a boatload of PDF safety documents, or a catalog of part pictures?
Well, then you can adopt and use what we call a "virtual" folder. They are pain to setup in IIS express, but REALLY easy to setup if you using IIS to setup and run the final server where you going to publish the site to.
Suffice to say, a virtual folder allows you to map a EXTERNAL folder into the root path name of your side.
So, you might have say a big server with a large number of PDF docuemnts,
say on
\\corporate-server1\PDF\Documents
so, in IIS, you can add the above path name, say as a folder called PDF.
Say like this:
So, WHEN you do the above, then the folder will appear like any plane jane folder in the root of the project, but the file paths can and will be on a complete different location OUTSIDE of the wwwroot folder for the web site.
So, now that we have the above all clear?
\\Mac\Home\Desktop\Homework3\Homework3\sx1l.txt
But, your code has this:
folderPath = Server.MapPath("~/Events");
File.WriteAllText(folderPath + eventFile, fullEventDetails);
(you missing the trailing "/" in above, you need this:
File.WriteAllText(folderPath + #"/" + eventFile, fullEventDetails);
So, that means the url for the text file will then be:
https://localhost:44399/Events/sx1l.txt
And if you using Visual Studio to add files to that folder (add->existing items), then MAKE SURE you Build->rebuild all (else the file will not be included in the debug run + launching of IIS express.
So, given that you saving into a folder called Events (as sub folder of wwwroot, or your base folder for hte web site, then the above is the url you should use, but your code always was missing that "/" between folder and file name.

SEC7134: Resource '...' not allowed to load. SCRIPT70: Permission denied

When using the below code to try to open File Explorer to a folder path I get the errors SEC7134: Resource 'file://...' not allowed to load, and SCRIPT70: Permission denied.
However if I copy the exact path returned in the error and past it into the url it opens a new file explorer window without any issues. This was working at one time for me as expected, I'm wondering if there have been security changes or things that need to be updated on my side to open these files in File Explorer again.
Thanks,
function openFile(path) {
// Internet Explorer 6-11
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
if (isIE || isEdge) {
window.location.href = path;
return false;
}
}
Yes, we could use the browser as file explorer to retrieve the files in our local environment. But, reading local files from the browser (using JavaScript) is not allowed. This will prevent websites reading files and stealing your information.
If you want to display the local file using JavaScript, you could use the upload control select the local file, then, read the file and display it.

fileupload C# get the exact path given [duplicate]

I am working on a web application which uses the FileUpload control. I have an xls file in the full filepath 'C:\Mailid.xls' that I am attempting to upload.
When I use the command
FileUpload1.PostedFile.FileName
I cannot get the full filepath from my system. However, when I use the above command in another system it works fine.
I also tried the following commands with no success:
System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
Path.GetFileName(FileUpload1.PostedFile.FileName);
System.IO.Path.GetDirectoryName(FileUpload1.PostedFile.FileName).ToString();
Convert.ToString(System.IO.Directory.GetParent(FileUpload1.PostedFile.FileName));
How can I get full path?
It's currently true that "when you upload a file the browser will only send the source filename and not the full path" - it makes perfect sense that the server has no business knowing whether the file was in "C:\WINDOWS\" or "F:\SOMEDIR\OTHERDIR\PERSONALINFO\". The filename is always sent, and is useful both to help the user 'recognise' the content and possibly to interrogate the file extension to help determine the file type.
However I know from experience that Internet Explorer definitely used to (in older versions) send the entire path. It's difficult to find an authoritative confirmation (except this apache fileupload control doco)
Internet Explorer provides the entire path to the uploaded file and not just the base file name
Regardless, you should not use nor expect the full path to be sent by any 'modern' browser.
Perhaps you misunderstand the way FileUpload works.
When you upload a file, it is effectively being transferred from the client's computer to the server hosting your application. If you're developing the application, most times, both client and server are the same machine (your computer). Once the application is deployed however, there could be any number of clients connecting to the server, each uploading a different file.
Knowing the full path of the file on the client's computer usually isn't necessary - you'll often want to do something with the file contents. Your examples seem like ASP.NET C#, so I'm guessing you're using the FileUpload control. You can get at the uploaded file's contents by reading the raw stream (FileUpload.PostedFile.InputStream) or by saving the file first (FileUpload.PostedFile.SaveAs), then accessing the saved file. It's your responsibility to save the file, if you want it to be accessible after the current request - if you don't, ASP.NET deletes it.
One more thing - don't forget to set the enctype property on your form to "multipart/form-data". If you don't, the client's browser won't send the file, and you'll spend quite a few minutes wondering what went wrong.
Try
Server.MapPath(FileUpload1.FileName);
Edit: This answer describes how to get the path to a file on the server. It does not describe how to get the path to a file on the client, which is what the question asked. The answer to that question is "you can't", because modern browser will not tell you the path on the client, for security reasons.
As of IE8, the full path is no longer sent to sites in the Internet Zone.
See the "File Upload Control" section at the end of this post: http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx for discussion.
FileUpload will never give you the full path for security reasons.
Convert.ToString(FileUpload1.PostedFile.FileName);
IE 7 and previous versions sent the full path of the uploaded file to the server related to the input type="file" field. Firefox and other modern browsers consider this to be a security flaw and do not. However, this appears to be have been fixed in IE 8.
Perhaps you should instead evaluate why you need the full path to the file as it was located on the client's system. I think it is really superfluous information that should never be posted at all. All you should be concerned with the is the file name so that you can save the file without making changes to the name.
Just to give my 2 cents.
At this moment I also DO get the full user's local path. It's only from 1 machine that I can replicate this issue, but it really does give the full path of the file at the machine of the user.
This is a end-user of our application which is hosted on a off-site server. So it's not on the local machine nor on a local server from which it might happen to be a share.
You can resolve the issue, at least to have the same behaviour all the time by this:
Path.GetFileName(fileUpload.FileName)
Btw, just found this article which states it can happen too: http://www.eggheadcafe.com/community/aspnet/17/10092650/fileupload-control-pro.aspx
Just to confirm the issue.
I had sort of the opposite issue as the original poster: I was getting the full path when I only wanted the filename. I used Gabriël's solution to get just the filename, but in the process I discovered why you get the full path on some machines and not others.
Any computer joined to domain will give you back the full path for the filename. I tried this on several different computers with consistent results. I don't have an explanation for why, but at least in my testing it was consistent.
Check this:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="FileUp.aspx.vb" Inherits="FileUp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label><br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<asp:Button ID="Button1" runat="server" Text="Upload" />
</div>
</form>
</body>
</html>
Code:
Partial Class FileUp
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim path As String
Dim path1 As String
path = Server.MapPath("~/")
FileUpload1.SaveAs(path + FileUpload1.FileName)
path1 = path + FileUpload1.FileName
Label1.Text = path1
Response.Write("File Uploaded successfully")
End Sub
End Class
This dumps the file in your temp folder with file name, then after that you can call it and not worry about it. Because it will get deleted if it is in your temp folder for an amount of days.
string filename = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(),".xls"));
File.WriteAllBytes(filename, FileUploadControl.FileBytes);
I'm using IE 8 (on two separate machines). Each still uploads the full local file path. As suggested by Gabriël, Path.GetFileName(fileUploadControl.PostedFile.FileName) appears to be the only way to ensure that you only get the filename.
Check this post under FileUpload Control
Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.
Its an option under Internet security that can be enabled
dim path as string = FileUpload1.PostedFile.FileName
By the way, I am using Visual Studio 2010. I don't know if there is a difference with the other version.
This will not problem if we use IE browser.
This is for other browsers, save file on another location and use that path.
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.PostedFile.FileName;
string TempfileLocation = #"D:\uploadfiles\";
string FullPath = System.IO.Path.Combine(TempfileLocation, fileName);
FileUpload1.SaveAs(FullPath);
Response.Write(FullPath);
}
Thank you
You can't get full path of a file at client's machine. Your code might work at localhost because your client and the server is the same machine and the file is at the root directory. But if you run it on a remote machine you will get an exception.
On Internet Explorer Options, on security tab click on custom security button, there have an option to send the local path when loading some file to server.
Disabled as default. Just enable it.
Path.GetFullPath(fileUpload.PostedFile.FileName);
Sorry this 'll get your program file directory + your file name.

How to check if a file exists on the web server

I have a file stored on the server and the web page I am populating depends on the fatc that the file exists or not.
How do I test if the file is available on the server?
The file comes on the web page as:
http://main.server.com/PGT/Reports/ObjectsReport.xml
I have to test the existence of this file and if it is available I will display a link otherwise I want to hide the link.
The actual path to the server is
//main.server.com/inetpub/wwwroot/PGT/Reports/ObjectsReport.xml
but I don't have access to the server (and therefore to the file) on the network. I can only access it using the web page. Is there a way to test that the server has the file or not display the link? (hlObjectsReport.Visible = false;)
I have tried to use the following:
Uri validatedUri;
Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validatedUri);
But it returns a valid address even if the file is not there.
Thanks
Tony.
use System.IO.File.Exists() (Documentation)
if(System.IO.File.Exists([path goes here]))
{
// do something
}
If you're not sure of the physical path, you can substitute the following for [path goes here] above:
Server.MapPath(/PGT/Reports/ObjectsReport.xml)
(Documentation)

how to refer images from the folder "c:\images" for setting src to img tag

i want to access the images from the system folders like (c:\,D:) for setting these images to the img src attribute. is it possible? how can it be achieved in asp.net?
Such local paths would only work for browsers on the same machine. They will NOT work for remote browsers, as those browsers will be attempting to access their OWN local drive, not your machine's.
But basically, simply use your browser to "surf" to the directory on your machine you want, then cut 'n paste the url bar. Just enter C:\ or D:\ as your starting location in the address bar.
<img src="file:///c:/images/sample.jpg">
If you need Remote Browser to have access at you're Local Drives or anywhere into the Harddrive than you should use SymLinks or HardLinks which can be created with the MLINK Command this is a how To
Because if you're ASP Application is located somwhere inside the C:// it can access only it's root dir and root sub dir's.
So just create a SymLink or HardLink from C:\images to you're ASP root directory .

Categories