C# filepath from fileuploader fails to be read by streamreader asp.net - c#

Running into an issue with a streamwriter
I have a web page that has a FileUploader in a loginview to access it I am using
var fileuploader = (FileUpload)LoginView.FindControl("FileUploader");
string filepath = System.IO.Path.GetFullPath(fileuploader.FileName.ToString());
Then I pass that data in to my streamreader which is (in a different class)
using (StreamReader reader = File.OpenText(filename))
The filepath that it is passing in is C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\sample.txt
Where I am selecting it from C:\fasta\sample.txt
I have seen some posts about this, but not concerning asp.net applications. Thanks!

The FileUpload class allows a client to upload/select a file. So all you can get would be a clientPath. Such a path would of no need to you! So what you can do is using the fileUpload.FileName property and combine it with some other path.
var fileuploader = (FileUpload)LoginView.FindControl("FileUploader");
string filepath = Path.Combine(Server.MapPath("."), fileuploader.FileName);
fileuploader.SaveAs(filePath); // will save the selected file on your server
Server.MapPath(..) maps a virtual path (at the server) to a real path at your server. Calling it with "." means this call will return your webApplication root directory. Anyway you should be very careful when uploading files where to save those! In worst case someone uploads a potential risky file (eg .aspx extension) and can execute code on your server!
Furthermore there is no need and no way to access a file at the client from the server directly. You may only get those items within the HTTP-Request. So the selectedFile is already in the Request and you can save it directly to your server harddisk!

I would suggest using the SaveAs method on the FileUpload control (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.fileupload.saveas.aspx).
Remember, the file is actually uploaded to you, and from a website, you'll never really want to care about the location it was at on the client machine (it just so happens the server and client are the same machine for you here). If you uploaded the file to the site from a different machine, the web server would never have access to the resource at the client's path. The FileUpload control has the file for you, so just take the file, place where you want, and then you can access it and do whatever you want with it.
Cliffs: even if you get the client path to the resource, your server won't be able to do anything with it since it is on another machine which your server doesn't have access to.

If you want to get the file uploaded:
.aspx
...
<asp:FileUpLoad id="FileUpLoad1" runat="server" />
...
code-behind
...
if (FileUpLoad1.HasFile)
{
FileUpLoad1.SaveAs(#"C:\temp\" + FileUpLoad1.FileName);
}
else
{
// No file uploaded
}
...
If you want the file path, the one that client had set in the browser control:
You can't. For security purposes, the browser will never post the full file's path.

Related

Could not find a part of the path error on file download

I've taken on an asp/c# web app to fix originally done by the previous developer at my workplace. The code shows a Gridview populated by results from a query showing a list of files, one column is made up of 'command fields' that when clicked download a file. Everything seems to go smoothly until it reaches the file download as it can't seem to find the file on the server. My C# really isn't strong so bear with me and if you need further info that I've missed out please do say so.
Here is the specific part of code that causes problems:
//strSuppDocName - is already declared elsewhere
string path = System.IO.Path.Combine(Server.MapPath("~/Documents/"), strSuppDocName);
if (!Directory.Exists(path)){
System.Windows.Forms.MessageBox.Show(path + " - file path doesn't exist");
}
else {
System.Net.WebClient client = new System.Net.WebClient();
Byte[] buffer = client.DownloadData(path);
if (buffer != null)
{
Response.ClearContent();
Response.ClearHeaders();
FileInfo file = new FileInfo(path);
Response.Clear();
Response.AddHeader("Content-Disposition", "Attachment;FileName:" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = ReturnExtension(strExtSuppDoc.ToLower());
Response.WriteFile(file.FullName);
Response.End();
}
}
What happens when I run the code is that the grid view populates okay, I click the file to download and it enters the first branch of the if statement showing the path. Before I added in the if statement it was showing the following error: "could not find a part of the path". I've tried fiddling with the path such as setting it absolutely:
string path = System.IO.Path.Combine(#"E:\web\Attestation\Documents\", strSuppDocName);
And without using the Combine method above and using standard string concatenation with '+'. Any help or guidance is most appreciated, thanks!
You're mixing a handful of technologies here. First of all, this doesn't belong in a web application:
System.Windows.Forms.MessageBox.Show(path + " - file path doesn't exist");
Web applications aren't Windows Forms applications. This won't display anything to someone using the web application, because there's no concept of a "message box" over HTTP.
More to the point, however, you're using path in two very different ways. Here:
Byte[] buffer = client.DownloadData(path);
and here:
FileInfo file = new FileInfo(path);
Is path a URL on the network or a file on the file system? It can't be both. The first line is treating it as a URL, trying to download it from a web server. The second line is treating it as a local file, trying to read it from the file system.
What is path and how are you looking to access it? If it's a URL, download it with the WebClient and stream it to the user. If it's a file, read it from the file system and stream it to the user. You can't do both at the same time.
If you are interacting with a path on a network (aka UNC path), you have to use Server.MapPath to turn a UNC path or virtual path into a physical path that .NET can understand. So anytime you're opening files, creating, updating and deleting files, opening directories and deleting directories on a network path, use Server.MapPath.
Example:
System.IO.Directory.CreateDirectory(Server.MapPath("\\server\path"));
The answer in short is that the file name was incorrect.
Strangely or mistakenly the author of the code, when uploading a given file, added an extra extension so a file would be something like 'image.png' to start off with then when uploaded would become image.png.png. Why didn't I notice this before you may ask? Simply because the whole path wasn't shown in Windows XP (don't ask why I was using XP) when viewing it through the explorer window and I dismissed this issue long before - a big mistake! After trying to find the file by typing the address of the file into the windows explorer address bar and receiving an error that the file doesn't exist, yet I could plainly see it did, a colleague looked at for the file remotely using Windows 7 and we saw that the file was shown as 'image.png.png'. Thereafter the path to the file worked correctly.

how to set local path in javascript of window.open by using in C#.net

i am trying to open the excel which was in local disc D path of my system since i have set this bellow string as such but it was not working in c#.net
string strScript = "<script language=JavaScript>window.open('file://D:/Ajman/FrameworkWebUI/Temp/ExcelFileName.xls',null,'width=1,height=1,toolbar=no,top=300,left=700,right=1, scrollbars=no,locaton=yes,resizable=1');</script>";
If the file is at the server location :
you should use a network based address file and not FILE system mode
e.g. :
\\myserver\files\aaa.jpg
Accessing local system's files are not allowed by design from javascript .This is a security measure.
JavaScript Security
However you may want to see TiddlyWiki
If you are using C# why don't you use it to get the file, why use javascript?
You could do something like this:
string filepath = Server.MapPath(name of the file);
//The file location must be accessible to the website
Then you could use the File or FileInfo classes to obtain the file
FileInfo file = new FileInfo(filepath);
//OR
File.Open(filepath, FileMode.Open))
You will only be able to access a file location on IE. IF you use any other browser it will not work. I think there is a registry hack to have Firefox do it, but to stay consistent across all browsers you might want to read the contents of the file on the server side and show it using a postback or AJAX.

How to get path to file in winforms application

How can I get the path of a file on my computer or on the local area network.
I would to show a window that allows me to browse the file system when I click a button, and I want to select a file and get the path to the file. How can I do this?
P.S. I'm not looking to upload the file; I just want to get the path.
The web application is running on the server, and you don't have access to the client file system at all. Can you imagine how much of a vulnerability that would be? I know I don't want the sites I visit inspecting my file system...
EDIT: Question is for a WinForms application
For a WinForms application, you can use the OpenFileDialog, and extract the path with something like this:
If you're looking for the file path:
string path = OpenFileDialog1.FileName; //output = c:\folder\file.txt
If you're looking for the directory path:
string path = Path.GetDirectoryName(OpenFileDialog1.FileName); //output = c:\folder
In general, the System.IO.Path class has a lot of useful features for retrieving and manipulating path information.
To do this in VB.NET use the FolderBrowserDialog.
Due to security restrictions browsers include for user safety, you can't manipulate the client file system directly. You can only use to let them pick a file, and even then it only sends the filename, not the whole path.
The FileSystem API in HTML5 allows for file manipulation, but only within a sandbox for your site specifically, not browsing across the network or other files on the client system.
Instead, provide your users easy steps on how they should use My Computer (or whatever equivalent on other OS's) to navigate to the file and copy & paste the path into a simple text input box.
Have you taken a look at the Path class from System.IO ?

How to upload files on server?

I have deployed my software on a server,In my software there is a tool which reads an excel file and displays the content in a gridView.
It's working fine on my stand-alone PC, how can I do it on the web?
Should I upload my excel files on server and then read it or directly read it from the user's PC?
Any solutions?
you need to put fileupload control on your page
<asp:FileUpload ID="fup" runat="server" />
and then in code behind, save this file
fup.SaveAs(Server.MapPath("~/upload/temp/" + fup.FileName ));
you can take a look at this article
Performing a File Upload using ASP.NET 2.0 and C# .NET
and Simple File Upload Control with ASP.NET and C#
I am not getting your question so far.Which error occurs on web?
Here is the sample code which may help you.
Every time it uploads excel file on server from client machine and get data from that and bind grid.
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
if (AsyncFileUpload1.HasFile)
{
string strPath = MapPath("~/Uploads/") + System.IO.Path.GetFileName(e.filename);
// gets extension of a file to check for a valid excel file
string ext = System.IO.Path.GetExtension(e.filename);
if (ext.ToLower() == ".xlsx" || ext.ToLower() == ".xls")
{
AsyncFileUpload1.SaveAs(strPath);
}
DataTable dt = getdata(strPath); // get data from excel file
BindGrid(dt);
}
}
You can't read it directly from users PC, you need to upload files anyway.
It's working fine on your local environment because effectively your website and the file you're trying to read are on the same machine. As a result, the web server can just load the file directly and there's no problem.
In a live environment, the website will be on a server somewhere while the excel file will be on the user's on own pc. In this scenario the web server can't access the file and you will have to upload to the web server by means of a file upload dialog. You can then save this file to a safe folder you specify (ideally in your web.config in case you change your mind or need to move it) somewhere on your server and access the file to display, manipulate or even insert into a database should you choose to.
I don't think you should save it to your server unless you really have to (which would require Write permissions on the directory you save to). If you are using Open XML to read the Excel file you can read the posted stream directly without saving to file first via SpreadsheetDocument.Open(FileUpload1.PostedFile.InputStream, false)...

C# Get Full File Path

I have an ASP FileUpload control and I am uploading:
C:\Documents and Settings\abpa\Desktop\TTPublisher\apache-tomcat-6.0.26\webapps\ttpub\WEB-INF\classes\org\gtfs\tmp\GTFS_Rail\routes.txt
What is the C# code to grab this entire string using the code below:
var pathOfCsvFile = Server.MapPath(ImportRoutes.FileName);
var adapter = new GenericParsing.GenericParserAdapter(pathOfCsvFile);
DataTable data = adapter.GetDataTable();
I know that Server.MapPath needs to change.
UPDATE:
Using System.IO.Path.GetFullPath gave me the below output:
pathOfCsvFile = "C:\\Program Files\\Common Files\\Microsoft Shared\\DevServer\\10.0\\routes.txt"
You are mixing up client and server behavior, which is easy to do when you are testing locally. The issue you are having is that the FileUploadControl (and HTML file uploading in general) is specifically designed to not provide you with the full path to the file. That would be a privacy breach. What it is designed to give you is the binary data of the file that was uploaded itself. Specifically you should query the properties on FileUploadControl: FileBytes or FileContent.
Just to further clarify the issue, what would happen if the browser user was actually on a physically different machine from the web server (the usual case)? What good would the full path of the file on the client machine be to you on the server?
Server.MapPath will return the physical path to a file in or below the application root. If that path you list is outside the application root, Server.MapPath will not work.
You can map a virtual directory to a folder you want to use to hold file uploads, which you can then discover with Server.MapPath.

Categories

Resources