How to upload files on server? - c#

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)...

Related

Open file directly from SharePoint path with CSOM

I have a SharePoint server and I want to open files directly from the Server with SharePoint CSOM.
User clicks button --> the file (Excel, Word, ...) opens at the client machine with the standard software.
Directly means, that if I change something to the file and click save, that the file is directly saved on the SharePoint server (or if I click e.g. 'Save as' in Excel the suggested path is 'https://sharpoint.url.com/folder').
Actually I have:
using Microsoft.SharePoint.Client;
var clientContext = new ClientContext("https://sharpoint.url.com");
string relativePath = "/folder/file.xls";
clientContext.Credentials = CredentialCache.DefaultCredentials;
var file = clientContext.Web.GetFileByServerRelativeUrl(relativePath);
clientContext.Load(file);
clientContext.ExecuteQuery();
What do I have to do now, if I want to open the file directly (no download)?
I assume you ask how to access the file's stream instead of downloading it to a local folder.
You can use the File.OpenBinaryDirect method to get access to its ETag and stream, eg :
using(var fileInfo=File.OpenBinaryDirect(clientContext,"/folder/file.xls"))
using(var reader=new StreamReader(fileInfo.Stream))
{
//Do whatever you want with the data
}
BTW you shouldn't use the old xls files. The format is deprecated for over 10 years. The current Excel format, xlsx, is a zipped package of XML files that's better supported by SharePoint itself, doesn't require Excel to generate or read.
For example, if you wanted to read cell values from an xlsx file, you could use the popular EPPlus library to read directly from the stream:
using(var fileInfo=File.OpenBinaryDirect(clientContext,"/folder/file.xlsx"))
using(var package=new ExcelPackage(fileInfo.Stream))
{
var sheet=package.Workbook.Worksheets[0];
var value=ws.Cells["A1"].Value;
//...
}
UPDATE
It seems the question isn't related to programming after all. All that's needed to save or open a SharePoint document is clicking on the document's link. What happens then depends on the Open Documents in Client Applications setting at the site and document library level.
This affects the headers the server sends to the browser when the user clicks on a document link. The browser may still refuse to open the registered application and display the Save dialog.
If that doesn't work, you should check why instead of writing code. It's probably a configuration error or a browser setting. Solving it is easier than creating workarounds, pushing them to all client machines. And then keeping track of all the patches, where they are deployed and deploying new ones.
Apart from that, the Office applications know about SharePoint and document libraries since 2003. They can browse them, display SharePoint properties for the document, show collaborators etc.
As I mentioned in the question comments, a lot of what people think as "SharePoint Developoment" is nothing more that configuration, administration and end user features.
MSDN docs don't help either - they actually cause harm by not covering SP administration or explaining the features and how they are used. You'll find that in Technet. For years, people created webparts in code to change how grids looked because MSDN didn't explain how eg the DataViewWebPart worked or how you could style a grid from the UI.
In general, the best place for such questions is http://sharepoint.stackexchange.com. For example, check “Open in the client application” Vs “Use the server default (Open in the client application)” inside the document library advance settings
We can create Map Network Drive for SharePoint library, and open the file from the network location. Check article below:
http://support.sherweb.com/Faqs/Show/how-to-connect-to-a-sharepoint-site-using-webdav-sharepoint-2013
Or we can download the file from SharePoint and open it using the code below:
Application.Workbooks.Open(#"C:\Test\YourWorkbook.xlsx");
Reference: https://msdn.microsoft.com/en-us/library/b3k79a5x.aspx

Issue in open excel from C# code

Am trying to read an excel in C# web application, The functionality is working fine when application is accessed with in the windows server hosted or when solution is tested in development machine.
But am getting below error when I access the application hosted on a server from a different system.
Please suggest, what could be the issue.
filePath = FileUpload.PostedFile.FileName;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(#filePath);
'C:\Users\xys\Desktop\xyz.xls' could not be found. Check the spelling
of the file name, and verify that the file location is correct. If you
are trying to open the file from your list of most recently used
files, make sure that the file has not been renamed, moved, or
deleted.
You might get this error if you are trying to browse a file from your local computer and try to read the file contents in code behind using the path.
To fix the issue, either read contents in the client side and pass the data to server side or place the file in a shared drive which is accessible from both client machine and server machine and then browse the file.

How to open a word , excel, or text document that is saved on a web server, using asp.net and c# [duplicate]

This question already has answers here:
How to implement a file download in asp.net
(2 answers)
Closed 6 years ago.
I am working on a ticketing system for my company using Asp.net and c#. User can create a ticket and attach a few documents to it (mostly word and excel documents). I upload and save the documents in the web server in a dedicated location (i.e. C:\Attachments).
Now, when user opens a previously created ticket, I show the list of the attachments as link buttons in a Gridview. I want user to be able to open the attachment by clicking on the link button. I have achieved this in my local machine in development, but when I publish the web app into IIS Server, I don't know how to open the files saved inside the web server. How do I provide the path for the file? Should I first download the file in the client machine and then open it? Any help is much appreciated.
This is how I open the attachment in development (which is the OnClick event of the link button):
protected void OpenAttachment(object sender, EventArgs e)
{
string FileName;
FileName = #"C:\Attachments\Test.docx";
Process.Start(FileName);
}
You have to change your approach in order to get the desired result.
Currently you create a new process on the web server by Process.Start. So you will see this process on your development environment because client and server are on the same computer.
In order to open a file by the browser, it has to be downloaded first. By adding the right content type, the browser can decide how to proceed with the downloaded file.
There are plenty of tutorials available. A starting point is this related StackOverflow question: How to implement a file download in asp.net

How to download Excel file from website using C# desktop application

I tried to use few method to download 1 excel file from website
I tried to use WebClient and DownloadFile... but it return 400 bad
request
I tried to use File.WriteAllBytes also kick in exception
My current workaround is call IExplorer with that particular file path ..then it will start to download(after user select file path)
Is that any way that i can straight download excel file without any notification?
Sample Excel Link: https://example.com/sr/XXX.issueviews:searchrequest-excel-all-fields/12345/SearchRequest-12345.xls?tempMax=1000

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

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.

Categories

Resources