开发者

Remote file download using .NET

开发者 https://www.devze.com 2023-01-04 06:55 出处:网络
I\'m trying to download remote file using C# (ASP.NET). The problem is when I browse to the file download URL - it downloads perfectly. When I try the WebClient.DownloadData(url) I get \"no data to sh

I'm trying to download remote file using C# (ASP.NET). The problem is when I browse to the file download URL - it downloads perfectly. When I try the WebClient.DownloadData(url) I get "no data to show" response.

If I browse using the built-in VS2010 browser I still get this "error" message.

The file link is: http://www.tase.co.il/TASE/Pages/Export.aspx?sn=he-IL_ds&enumTblType=AllSecurities&Columns=he-IL_Columns&Titles=he-IL_Titles&TblId=0&ExportType=3 开发者_如何转开发(CSV file)

How can the file be downloaded? any ideas?

Many Thanks


This isn't a download problem on your side, that page is referencing something, probably from session...so you would need to login to the site, get a session, basically go through whatever steps you normally would in route to getting the file so it's generated correctly/available.

If I had to take a guess, I'm thinking they do the export to the file system when you ask for it, so it's a temp file somewhere...not something you can just grab, so unless you went through the step that created it (doesn't seem this Export.aspx page does it), it won't be there, and their error message for this is "No data to show".

There's also the possibility they're explicitly blocking you to prevent any kind of bots/leeching from happening...basically preventing exactly what you're trying to do.


Many sites will block downloads based on the Referer or User-Agent header.

  1. Watch a "working" download with Fiddler
  2. Watch your code's download with Fiddler
  3. Compare the two requests
  4. Update your request to match the "working" case.


I solved the problem by obtaining the remote file as a stream. From that point I was able to read/write the stream to the response.

//The absolute path to your file
string remoteFile = "http://my.cloudfront.net/videos/vehicle_english_v3.mp4";

//The name of the file you want the user to see when they download the file
int pos = remoteFile.LastIndexOf("/") + 1;
string fileName = remoteFile.Substring(pos, remoteFile.Length - pos);

//Obtain your file as a stream
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteFile);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream fileStream = response.GetResponseStream();

//Write the stream to the response
if (fileStream != null && fileStream.CanRead) {
    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    context.Response.ContentType = "application/octet-stream";
    context.Response.ClearContent();
    fileStream.CopyTo(context.Response.OutputStream);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号