title: C# HttpWebRequest POST data in chunk
body: <p>What is the max length of <strong>byte array</strong>?  I'm trying to create an array of bytes whose length is <strong>551858003</strong>. I have created on zip file of near about 526 MB. But it gives me error <code>Out of memory exception</code> I am uploading the file on <code>google drive</code>.</p>
  
  <p>Here I tried some code. I am reading the bytes of zip file by using following code.</p>
  
  <pre><code> byte[] FileByteArray = null;
  
                  using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
                  {
                      if (storage.FileExists(fileName))
                      { 
                          using (IsolatedStorageFileStream fileStream = storage.OpenFile(fileName,FileMode.Open,FileAccess.Read))
                          {
                              fileStream.Flush();
                              fileStream.Position = 0;
                              long len = fileStream.Length;
                              FileByteArray = new byte[len];
                              fileStream.Read(FileByteArray, 0, FileByteArray.Length);
  
                              //using (BinaryReader binReader = new BinaryReader(fileStream))
                              //{
                              //    Int32 Filelength = Convert.ToInt32(fileStream.Length);
                              //    FileByteArray = binReader.ReadBytes(Filelength);
                              //}
                              fileStream.Flush();
                              fileStream.Dispose();
                              fileStream.Close();
                          }
                      }
                  }
  </code></pre>
  
  <p>How can I resolve this issue ? I am getting <code>OutOfMemoryException</code> while uploading large file. I can upload near about 100MB. </p>
  
  <p>Here is my Method for sending images in <code>chunk</code></p>
  
  <pre><code> public void Images_ChunkRequst(string uploadURL, byte[] FileByteArray, int startIndex)
      {
          try
          {
              int chunkSize = 256 * 1024 * 2;
              int totalChunks = (int)Math.Ceiling((double)FileByteArray.Length / chunkSize);
              int endIndex = (int)(startIndex + chunkSize &gt; FileByteArray.Length ? FileByteArray.Length : startIndex + chunkSize);
              int length = endIndex - startIndex;
  
              if (i &lt; totalChunks)
              {
                   CollectionIP = CheckInternet.Find();
                  if (CollectionIP.Count == 2 &amp;&amp; DeviceNetworkInformation.IsWiFiEnabled)
                      NetworkIPaddress = IPAddress.Parse(CollectionIP[1]).ToString();
                  else if (CollectionIP.Count &gt; 0 &amp;&amp; DeviceNetworkInformation.IsWiFiEnabled)
                      NetworkIPaddress = IPAddress.Parse(CollectionIP[0]).ToString();
  
                  if (!string.IsNullOrEmpty(NetworkIPaddress))
                  {
                      i = i + 1;
                      var request = WebRequest.Create(uploadURL) as HttpWebRequest;
                      request.Method = "PUT";
                      request.Headers["Authorization"] = string.Format("Bearer {0} ", AccessToken);
                      request.ContentType = "application/zip";
                      request.ContentLength = length;
                      request.Headers["Content-Range"] = "bytes " + startIndex + "-" + (endIndex - 1) + "/" + FileByteArray.Length;                        
                      request.AllowWriteStreamBuffering = false;
  
                      request.BeginGetRequestStream(arPut =&gt;
                      {
                          var request1 = (HttpWebRequest)arPut.AsyncState;
                          using (var dataStream = request1.EndGetRequestStream(arPut))
                          {
                              //getting exception here
                              dataStream.Write(FileByteArray.Skip(startIndex).Take(endIndex).ToArray(), 0, FileByteArray.Take(length).Count());                                
                              dataStream.Flush();
                              dataStream.Dispose();
                              dataStream.Close();
                          }
                          request1.BeginGetResponse(aPut =&gt;
                          {
                              var request2 = (HttpWebRequest)aPut.AsyncState;
                              WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
                              WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
                              var response = (HttpWebResponse)request2.EndGetResponse(aPut);
  
                              if (response.StatusCode.ToString() == "308") // Resume Incomplete
                              {
                                  response.Dispose();
                                  response.Close();
  
                                  string packet = response.Headers["Range"];
                                  string[] rng = packet.Remove(0, 6).Split('-');
                                  Images_ChunkRequst(uploadURL, FileByteArray, Convert.ToInt32(rng[1]) + 1);
                              }
                              else if (response.StatusCode.ToString() == "500") //Internal Server Error
                              {
                                  i = i - 1;
                                  response.Dispose();
                                  response.Close();
                                  Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
                              }
                              else if (response.StatusCode.ToString() == "502") //Bad Gateway
                              {
                                  i = i - 1;
                                  response.Dispose();
                                  response.Close();
                                  Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
                              }
                              else if (response.StatusCode.ToString() == "503") //Service Unavailable
                              {
                                  i = i - 1;
                                  response.Dispose();
                                  response.Close();
                                  Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
                              }
                              else if (response.StatusCode.ToString() == "504") //Gateway Timeout
                              {
                                  i = i - 1;
  
                                  response.Dispose();
                                  response.Close();
                                  Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
                              }
                              else if (response.StatusCode == HttpStatusCode.NotFound) //Not Found
                              {
                                  i = i - 1;
  
                                  response.Dispose();
                                  response.Close();
                                  Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
                              }
                              else if (response.StatusCode == HttpStatusCode.OK) // upload complete.
                              {
                                  Dispatcher.BeginInvoke(() =&gt;
                                  {
                                      i = 0;// i must be 0 after each upload success
                                      imgPass_Images.Visibility = Visibility.Visible;
                                      this.LayoutRoot.IsHitTestVisible = true;
                                      SystemTray.ProgressIndicator.IsIndeterminate = false;
                                      SystemTray.IsVisible = false;
                                      GetNextAutoOrder();
                                  });
                              }
                          }, request1);
                      }, request);
                  }
                  else
                  {
                      this.LayoutRoot.IsHitTestVisible = true;
                      SystemTray.ProgressIndicator.IsIndeterminate = false;
                      SystemTray.IsVisible = false;
                      MessageBox.Show("Please check your internet connection.");
                  }
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show("Error occured. Trying to send failed package.");
              Images_ChunkRequst(uploadURL, FileByteArray, startIndex);
          }
      }
  </code></pre>
  
  <p>I am getting exception here <code>dataStream.Write(FileByteArray.Skip(startIndex).Take(endIndex).ToArray(), 0, FileByteArray.Take(length).Count());</code>. I have tried lot to solve this issue. Can some one please help me? I am getting this exception <code>Insufficient memory to continue the execution of the program</code></p>