C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: This example writes a PNG image to the Default.aspx page when run. This is rendered in the browser window.
Page that uses BinaryWrite: C#
using System;
using System.IO;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// 1.
// Get path of byte file.
string path = Server.MapPath("~/Adobe2.png");
// 2.
// Get byte array of file.
byte[] byteArray = File.ReadAllBytes(path);
// 3A.
// Write byte array with BinaryWrite.
Response.BinaryWrite(byteArray);
// 3B.
// Write with OutputStream.Write [commented out]
// Response.OutputStream.Write(byteArray, 0, byteArray.Length);
// 4.
// Set content type.
Response.ContentType = "image/png";
}
}
Info: BinaryWrite is a public instance method. OutputStream.Write is an abstract method.
Public, privateAbstractImplementation: IL
callvirt instance void [mscorlib]System.IO.Stream::Write(uint8[], int32, int32)
Note: The performance difference here is not relevant to most websites. And you may need to retest it.
BinaryWrite performance test result
Response.OutputStream.Write: 293.60 ms
Response.BinaryWrite: 313.94 ms
Page that benchmarks BinaryWrite: C#
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());
}
}
And: We examined the micro-benchmark. We found using OutputStream.Write is more efficient.