/// <summary> /// Will stream a file to the client. /// </summary> private void SendFile(Guid requestId, HttpListenerContext context, string file) { HttpListenerResponse response = context.Response; response.SendChunked = true; response.StatusCode = (int)HttpStatusCode.OK; response.ContentType = RegistryHelpers.GetContentType(file); using (Stream local = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { // response.ContentLength64 = local.Length; Stream client = response.OutputStream; byte[] data = new byte[_chunkSize]; int bytesRead = 0; DateTime chunkStart; DateTime start = DateTime.Now; while (local.Position < local.Length) { chunkStart = DateTime.Now; bytesRead = local.Read(data, 0, _chunkSize); try { client.Write(data, 0, bytesRead); client.Flush(); // balance of time to wait ThrottleByteRate(chunkStart); } catch (HttpListenerException hle) { TraceMessage(requestId, "Error sending chunk {0}-{1}/{2}. {3}", local.Position - bytesRead, local.Position, local.Length, hle.Message); return; // will ab end } } response.Close(); double elapsed = DateTime.Now.Subtract(start).TotalMilliseconds; TraceMessage( requestId, "Request of {1} bytes completed in {0}ms at {2} Kbps.", elapsed, local.Length, (float)local.Length * 8 / 1024 // bytes * (bits per byte) / Kilo / (elapsed / 1000)); // divided by milliseconds / (milliseconds per second) } }