c# - 从带有进度条的 URL 下载 Json 文件
问题描述
我需要从 url 下载大型 json 文件。它使用 post 方法,带有参数、用户名、密码等。
由于需要很长时间,我尝试放置一个进度条,以便用户可以看到它走了多远,还剩下多少。
问题
在下载之前,我无法从 url 检索 Json 文件的内容长度。请参阅下面代码中注释的错误。有什么建议么 ?
public void downloadJson(string Url, string UserName, string Password, string FileDownload)
{
HttpWebRequest httpRequest;
HttpWebResponse httpResponse;
int Size;
var json = string.Format("{{\"user\":\"{0}\",\"pwd\":\"{1}\",\"DS\":\"KG\"}}", UserName, Password);
httpRequest = (HttpWebRequest)WebRequest.Create(Url);
httpRequest.Method = WebRequestMethods.Http.Post;
httpRequest.ContentLength = json.Length;
httpRequest.ContentType = "application/json";
httpRequest.Timeout = 600 * 60 * 1000;
var data = Encoding.ASCII.GetBytes(json); // or UTF8
using (var s = httpRequest.GetRequestStream())
{
s.Write(data, 0, data.Length);
s.Close();
}
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Size = (int)httpResponse.ContentLength;
Stream rs = httpResponse.GetResponseStream();
//**********************************************
//Here is the error
//the below progress bar would never work
//Because Size returned from above is always -1
//**********************************************
progressBar.Invoke((MethodInvoker)(() => progressBar.Maximum = Size));
using (FileStream fs = File.Create(FileDownload))
{
byte[] buffer = new byte[16 * 1024];
int read;
int position;
using (rs)
{
while ((read = rs.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, read);
position = (int)fs.Position;
progressBar.Invoke((MethodInvoker)(() => progressBar.Value = position));
Console.WriteLine ("Bytes Received: " + position.ToString());
}
}
fs.Close();
}
解决方案
错误可能在这里;
大小 = (int)httpResponse.ContentLength;
我相信当你声明 like int Size; 您想分配整数数据类型 Size
但似乎 Size 的行为不像整数数据类型。
尝试将 Size 更改为类似 siz 的值,然后再试一次。
推荐阅读
- parse-cloud-code - Back4App 部署带有 .js 文件问题的文件夹
- sql - 除以我的查询中遇到的零错误
- javascript - 不知道为什么长度未定义
- sql - 在 Oracle SQL Live 中使用 alter 添加多个外键
- javascript - D3 将对象传递给 .attr 或 .style
- javascript - 列表和样式中的反应备忘录问题
- macos - 用于 mac 的 Silabs CP210x 驱动程序无法正常工作。- 2月21日
- excel - 在 vb.net 中读取扩展名为 .xlsb 的 Excel 文件
- visual-studio-code - VSCODE.window.showInputBox 是否提供了一种通过消息拒绝输入并重新提示的方法?
- java - 如何制作自定义日期格式,该格式将根据区域设置(美国或英国)更改 MMdd 订单