C# 如何使用 HttpWebRequest/Response 从 Web 服务器下载二进制 (.exe) 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14192993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How To Use HttpWebRequest/Response To Download A Binary (.exe) File From A Web Server?
提问by Jan Tacci
I am writing a program that needs to download an .exe
file from a website and then save it to the hard drive. The .exe
is stored on my site and it's url is as follows (it's not the real uri just one I made up for the purpose of this question):
我正在编写一个程序,需要.exe
从网站下载文件,然后将其保存到硬盘驱动器。将.exe
存储在我的网站,它的网址如下(这不是真正的URI只是一个我提出了对这个问题的目的):
http://www.mysite.com/calc.exe
After many web searches and fumbling through examples here is the code I have come up with so far:
经过多次网络搜索和摸索示例之后,我到目前为止想出了代码:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(http://www.mysite.com/calc.exe);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string s = streamReader.ReadToEnd();
As you can see I am using the StreamReader
class to read the data. After calling ReadToEnd
does the stream reader contain the (binary) content of my .exe? Can I just write the content of the StreamReader
to a file (named calc.exe) and I will have succesfully downloaded the .exe?
如您所见,我正在使用StreamReader
该类来读取数据。调用后ReadToEnd
流阅读器是否包含我的 .exe 的(二进制)内容?我可以StreamReader
将 .exe的内容写入文件(名为 calc.exe),然后成功下载 .exe 吗?
I am wondering why StreamReader
ReadToEnd
returns a string. In my case would this string be the binary content of calc.exe?
我想知道为什么StreamReader
ReadToEnd
返回一个字符串。在我的情况下,这个字符串是 calc.exe 的二进制内容吗?
回答by VinayC
StreamReaderis a text reader implementation i.e. it should be used to read text data and not binary data. In your case, you should be directly using the underlying response stream.
StreamReader是一个文本阅读器实现,即它应该用于读取文本数据而不是二进制数据。在您的情况下,您应该直接使用底层响应流。
For downloading file, the simplest way would be to use WebClient.DownloadFilemethod.
对于下载文件,最简单的方法是使用WebClient.DownloadFile方法。
回答by dotNET
Instead of using StreamReader
, you should really call Read()
method of your Stream
object. That will ask you for a byte[] buffer to be fill with read data, which you can then write to disk using StreamWriter
or FileStream
.
StreamReader
您应该真正调用对象的Read()
方法,而不是使用Stream
。这将要求您使用 byte[] 缓冲区填充读取数据,然后您可以使用StreamWriter
or将其写入磁盘FileStream
。
回答by user2492339
This should directly save the file on your hard disk.
这应该直接将文件保存在您的硬盘上。
using System.Net;
using (WebClient webClient = new WebClient ())
{
webClient.DownloadFile("http://www.mysite.com/calc.exe", "calc.exe");
}
回答by Dipu
WebClient is the best method to download file. But you can use the following method to download a file asynchronously from web server.
WebClient 是下载文件的最佳方法。但是您可以使用以下方法从 Web 服务器异步下载文件。
private static void DownloadCurrent()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("[url to download]");
webRequest.Method = "GET";
webRequest.Timeout = 3000;
webRequest.BeginGetResponse(new AsyncCallback(PlayResponeAsync), webRequest);
}
private static void PlayResponeAsync(IAsyncResult asyncResult)
{
long total = 0;
long received = 0;
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
try
{
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
byte[] buffer = new byte[1024];
FileStream fileStream = File.OpenWrite("[file name to write]");
using (Stream input = webResponse.GetResponseStream())
{
total = input.Length;
int size = input.Read(buffer, 0, buffer.Length);
while (size > 0)
{
fileStream.Write(buffer, 0, size);
received += size;
size = input.Read(buffer, 0, buffer.Length);
}
}
fileStream.Flush();
fileStream.Close();
}
}
catch (Exception ex)
{
}
}
There is a similar thread here - how to download the file using httpwebrequest
这里有一个类似的线程 -如何使用 httpwebrequest 下载文件
回答by ThexBasic
I'm probably a little bit late but I had the same problem with files being always 0kb big if not running in Debug mode.. This might be a relatively simple answer but disabling "DEBUG-Constants" under Properties solved it for me.
我可能有点晚了,但我遇到了同样的问题,如果不在调试模式下运行,文件总是 0kb 大。这可能是一个相对简单的答案,但在属性下禁用“DEBUG-Constants”为我解决了这个问题。