Response.BinaryWrite
BinaryWrite
outputs binary data to the Response. It is used to write a byte
array—which can represent a file cached in memory.
We look at the basics of the BinaryWrite
method in ASP.NET. We explore its performance—and how it uses an abstract
method call.
Here we write binary data to the Response in ASP.NET. We call BinaryWrite
and OutputStream.Write
. The 2 code parts here do the same thing.
Default.aspx
page when run. This is rendered in the browser window.using System; using System.IO; using System.Web.UI; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { // Get path of byte file. string path = Server.MapPath("~/Adobe2.png"); // Get byte array of file. byte[] byteArray = File.ReadAllBytes(path); // Write byte array with BinaryWrite. Response.BinaryWrite(byteArray); // Write with OutputStream.Write [commented out] // Response.OutputStream.Write(byteArray, 0, byteArray.Length); // Set content type. Response.ContentType = "image/png"; } }
Here we compare calling BinaryWrite
on Response, to calling Response.OutputStream.Write
. OutputStream.Write
is an abstract
method on the Stream
.
OutputStream.Write
seemed to be faster. In 2022, this should be retested as the data is too old.using System; using System.Diagnostics; using System.Text; using System.Web; using System.Web.UI; using System.IO; public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { byte[] b = new byte[1]; HttpResponse r = Response; StringBuilder builder = new StringBuilder(); Stopwatch stop = new Stopwatch(); // Stream output = r.OutputStream; for (int i = 0; i < 50; i++) // Also tested with Test 2 first. { stop = Stopwatch.StartNew(); // Test 1 for (int v = 0; v < 3000000; v++) { r.OutputStream.Write(b, 0, b.Length); // output.Write(b, 0, b.Length); <-- faster for another reason } // End stop.Stop(); long ms1 = stop.ElapsedMilliseconds; r.ClearContent(); stop = Stopwatch.StartNew(); // Test 2 for (int v = 0; v < 3000000; v++) { r.BinaryWrite(b); } // End stop.Stop(); long ms2 = stop.ElapsedMilliseconds; r.ClearContent(); builder.Append(ms1).Append("\t").Append(ms2).Append("<br/>"); } r.Write(builder.ToString()); } }Response.OutputStream.Write: 293.60 ms Response.BinaryWrite: 313.94 ms
We peek into IL Disassembler and see how BinaryWrite
is implemented on Response. You can see that BinaryWrite
simply receives the byte[]
buffer.
OutputStream.Write
with three parameters based on the buffer.BinaryWrite
is a public instance method. OutputStream.Write
is an abstract
method.We looked at the BinaryWrite
method in ASP.NET. First we saw some basic usage of it, and then tested the performance of the method.