HttpWebRequest request = (HttpWebRequest)WebRequest.Create("request_uri_string");
FileStream fileStream = new FileStream("path_to_my_file", FileMode.Open, FileAccess.Read);
Stream requestStream = request.GetRequestStream();
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 1;
while (bytesRead != 0)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
request.Close();
fileStream .Close();
目前我正在使用上面的代码。
还有比这更好(意味着快速)的其他方法吗?
不确定这是否更快,但可读性更高:
using (var webClient = new WebClient())
{
webClient.DownloadFile(remoteFileUrl, localFileName);
}
编辑:
因为 WebClient
是 IDisposable
,所以应该正确处理它(我添加了 using
)。
MSDN 说:
This method uses the RETR
command to download an FTP resource. For an HTTP resource, the GET
method is used.
我是一名优秀的程序员,十分优秀!