我正在尝试使用WebClient.UploadFile将文件上传到HTTP URL .对于1M,2M等小文件,上传成功.但是对于像12M这样的大文件,我得到了这个例外:
The request was aborted: The request was canceled.
Run Code Online (Sandbox Code Playgroud)
有没有人以前遇到过这个问题,你能分享一下解决方案吗?
这是smwikipedia的答案中提到的解决方案.我添加了禁用写入流缓冲的功能,这可以帮助解决内存不足异常问题.
public class ExtendedWebClient : WebClient
{
public int Timeout { get; set; }
public new bool AllowWriteStreamBuffering { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request != null)
{
request.Timeout = Timeout;
var httpRequest = request as HttpWebRequest;
if (httpRequest != null)
{
httpRequest.AllowWriteStreamBuffering = AllowWriteStreamBuffering;
}
}
return request;
}
public ExtendedWebClient()
{
Timeout = 100000; // the standard HTTP Request Timeout default
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var webClient = new ExtendedWebClient();
webClient.Timeout = Timeout.Infinite;
webClient.AllowWriteStreamBuffering = false;
webClient.UploadFile(url, filePath);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4560 次 |
| 最近记录: |