title: Limit download size in RestSharp
body: <p>We're using RestSharp v105.2.3.</p>
  
  <p>Is there a way to stop receiving a response after N bytes have been received, where N is a parameter I can control?</p>
  
  <hr>
  
  <p>Edit: here is my complete solution based on Berin's answer below.</p>
  
  <pre><code>public static class IRestClientExtensions
  {
      public static IRestResponse Execute(this IRestClient client, IRestRequest request, byte[] buffer, out int bufferSize)
      {
          var totalBytesRead = 0;
  
          request.ResponseWriter = stream =&gt;
          {
              while (totalBytesRead &lt; buffer.Length)
              {
                  var bytesRead = stream.Read(buffer, totalBytesRead, buffer.Length - totalBytesRead);
                  if (bytesRead == 0)
                  {
                      break;
                  }
  
                  totalBytesRead += bytesRead;
              }
          };
  
          var response = client.Execute(request);
  
          bufferSize = totalBytesRead;
          return response;
      }
  }
  </code></pre>
  
  <p>Unit tests (using NUnit):</p>
  
  <pre><code>[TestFixture]
  public class IRestClientExtensionsTests
  {
      [Test, Explicit]
      public void Execute_OutputBufferTooSmall()
      {
          var client = new RestClient("https://www.w3.org/TR/html4/charset.html");
          var request = new RestRequest();
  
          var buffer = new byte[4 * 1024];
          int bufferSize;
          var response = client.Execute(request, buffer, out bufferSize);
  
          Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
          Assert.IsTrue(string.IsNullOrEmpty(response.Content));
          Assert.AreEqual(buffer.Length, bufferSize);
      }
  
      [Test, Explicit]
      public void Execute_OutputBufferLargeEnough()
      {
          var client = new RestClient("https://www.w3.org/TR/html4/charset.html");
          var request = new RestRequest();
  
          var buffer = new byte[256 * 1024];
          int bufferSize;
          var response = client.Execute(request, buffer, out bufferSize);
  
          Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
          Assert.IsTrue(string.IsNullOrEmpty(response.Content));
          Assert.IsTrue(bufferSize &lt; buffer.Length);
      }
  }
  </code></pre>