title: Download Json file from URL with progressbar
body: <p>I need to download large json files from url. It uses post method, with parameter, username, password, etc.</p>
  
  <p>As it takes quite long time, I try to put a progressbar, so users can see how far it has gone, and how much is left.</p>
  
  <p><strong>Problem</strong></p>
  
  <p>I am not able to retrieve the content length of the Json file from url before the download. Please see error commented in the code below. Any suggestions ?</p>
  
  <pre><code>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)(() =&gt; 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)) &gt; 0)
              {
                  fs.Write(buffer, 0, read);
                  position = (int)fs.Position;
                  progressBar.Invoke((MethodInvoker)(() =&gt; progressBar.Value = position));
                  Console.WriteLine ("Bytes Received: " + position.ToString());
              }
          }
  
          fs.Close();
      }
  </code></pre>