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

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

Related

How to download magnet link with C#?

Im working on a project which i need to download a magnet link from torrent websites. For example i give the magnet link to a text box and it downloads the content of that magnet link in the specified folder.
I wanted to use monotorrent but it was very complicated and it actually didnt work and it just throw some errors and one of them was "URI prefix is not recognized" and didnt know how to solve it.
and again, all i want to do is to download the magnet link and maybe show the progress with the progress bar
How can I implement such a program with C#?
Using Process.Start() will open the magnet URL with the default application set for handling them. It won't open in your application, but then you'd be writing a torrent application (which is not the easiest task...):
string magnetUrl = "magnet:?xt=urn:sha1: ..."
Process.Start(magnetUrl);
The best way would be programmaticaly downloading torrent file and then run a program with parameter which is the path to torrent file. For example you could use cygwin with rtorrent (command-line torrent client)

Exception of Unauthorized while using MostRecentlyUsedList in metro apps

I am working with Store apps using C#.
I am using StorageApplicationPermissions.MostRecentlyUsedList to load Local Epub files.
After getting those file as a Storage file.
string EpubPathToken= Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file);
StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(EpubPathToken);
Extraction(file);
While Extracting the Epub file as Zip to Package folder using ApplicationData I am getting an Exeption of Unauthorized.
Here's screen shot of error
Why because If I use the same code using from KnownFolders like Pictures Library the Extraction is working Fine.
Can any one give me any idea about this ?
Finally I solved the issue of getting exception of Unauthorized With the use of Blog
I changed the code snippet according to my requirement.
The source of code describes writes bytes of file in ZipArchiveEntry,
hence I used a helper method GetByteFromFile(), which takes StorageFile object and returns me byte[] array.
Finally thanks to Xyroid

Downloading a file in C# incorrectly returns files that is zero bytes long

So I'm trying to Download a file using WebClient class but the problem is that when the download is finished the file that should be downloaded is 0 byte, I tried uploading the same file without extension and than changing it after download but that didn't help. What Can I do? This is the code I Use
WebClient updateDownloader = new WebClient();
updateDownloader.DownloadFile(new Uri("http://zazaia.ucoz.com/SomeExeFile.exe"),
Application.StartupPath + "\\SomeFile.EXE");
And also have DownloadCompleted event handler which just shows MessageBox and Disposes the WebClient.
There is nothing wrong with the code you have shown and this should work. The problem is on the server which is not returning the file properly. Also make sure that the site you are querying doesn't require some authentication before being able to download files. In addition to that don't forget that a WebClient will not execute any javascript, so if the server relies on it to download the file, this will not happen.
Have you checked that your antivirus is not interfering? Sometimes an automatic scan will lock an executable file being downloaded until it passes. The client code itself looks fine however.
What about the server side? If is one of your own applications serving the download, then it may not be setting the MIME header or even not handling the download correctly at all

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

How To Do a Server To Server File Transfer without any user interaction?

In my scenario, users are able to upload zip files to a.example.com
I would love to create a "daemon" which in specified time intervals will move-transfer any zip files uploaded by the users from a.example.com to b.example.com
From the info i gathered so far,
The daemon will be an .ashx generic handler.
The daemon will be triggered at the specified time intervals via a plesk cron job
The daemon (thanks to SLaks) will consist of two FtpWebRequest's (One for reading and one for writing).
So the question is how could i implement step 3?
Do i have to read into to a memory() array the whole file and try to write that in b.example.com ?
How could i write the info i read to b.example.com?
Could i perform reading and writing of the file at the same time?
No i am not asking for the full code, i just can figure out, how could i perform reading and writing on the fly, without user interaction.
I mean i could download the file locally from a.example.com and upload it at b.example.com but that is not the point.
Here is another solution:
Let ASP.Net in server A receive the file as a regular file upload and store it in directory XXX
Have a windows service in server A that checks directory XXX for new files.
Let the window service upload the file to server B using HttpWebRequest
Let server B receive the file using a regular ASP.Net file upload page.
Links:
File upload example (ASP.Net): http://msdn.microsoft.com/en-us/library/aa479405.aspx
Building a windows service: http://www.codeproject.com/KB/system/WindowsService.aspx
Uploading files using HttpWebRequest: Upload files with HTTPWebrequest (multipart/form-data)
Problems you gotto solve:
How to determine which files to upload to server B. I would use Directory.GetFiles in a Timer to find new files instead of using a FileSystemWatcher. You need to be able to check if a file have been uploaded previously (delete it, rename it, check DB or whatever suits your needs).
Authentication on server B, so that only you can upload files to it.
To answer your questions - yes you can read and write the files at the same time.
You can open an FTPWebRequest to ServerA and a FTPWebRequest to ServerB. On the FTPWebRequest to serverA you would request the file, and get the ResponseStream. Once you have the ResponseStream, you would read a chunk of bytes at a time, and write that chunck of bytes to the serverB RequestStream.
The only memory you would be using would be the byte[] buffer in your read/write loop. Just keep in mind though that the underlying implementation of FTPWebRequest will download the complete FTP file before returning the response stream.
Similarly, you cannot send your FTPWebRequest to upload the new file until all bytes have been written. In effect, the operations will happen synchronously. You will call GetResponse which won't return until the full file is available, and only then can you 'upload' the new file.
References:
FTPWebRequest
Something you have to take into consideration is that a long running web requests (your .ashx generic handler) may be killed when the AppDomain refreshes. Therefore you have to implement some sort of atomic transaction logic in your code, and you should handle sudden disconnects and incomplete FTP transfers if you go that way.
Did you have a look at Windows Azure before? This cloud platform supports distributed file system, and has built-in atomic transactions. Plus it scales nicely, should your service grow fast.
I would make it pretty simple. The client program uploads the file to server A. This can be done very easily in C# with an FtpWebRequest.
http://msdn.microsoft.com/en-us/library/ms229715.aspx
I would then have a service on server A that monitors the directory where files are uploaded. When a file is uploaded to that directory or on certain intervals it simply copies files over to server B. Again this can be done via Ftp or other means if they're on the same network.
you need some listener on the target domain, ftp server running there, and on the client side you will use System.Net.WebClient and UploadFile or UploadFileAsync to send the file. is that what you are asking?
It sounds like you don't really need a webservice or handler. All you need is a program that will, at regular intervals, open up an FTP connection to the other server and move the files. This can be done by any .NET program with the System.WebClient library, doesn't have to be a "web app". This other program could be a service, which could handle its own timing, or a simple app run by your cron job. If you need this to go two ways, for instance if the two servers are mirrors, you simply have the same app on the second box doing the same thing to upload files over to the first.
If both machines are in the same domain, couldn't you just do file replication at the OS level?
DFS
set up keys if you are using linux based systems:
http://compdottech.blogspot.com/2007/10/unix-login-without-password-setting.html
Once you have the keys working, you can copy the file from system A to system B by writing regular shell scripts that would not need any user interactions.

Categories

Resources