首页 > 解决方案 > 从带有进度条的 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();
    }

标签: c#jsondownloadprogress-barhttpwebresponse

解决方案


错误可能在这里;

大小 = (int)httpResponse.ContentLength;

我相信当你声明 like int Size; 您想分配整数数据类型 Size

但似乎 Size 的行为不像整数数据类型。

尝试将 Size 更改为类似 siz 的值,然后再试一次。


推荐阅读