public static ActionResult SendFile(this HttpListenerResponse response, FileResponse r) { response.StatusCode = 200; //content-type response.ContentType = r.ContentType; //Range response.Headers["Accept-Ranges"] = "bytes"; long start = r.Start; long end = 0; if (!string.IsNullOrEmpty(r.Range)) { Match m = Regex.Match(r.Range, @"(?<start>\d+)\-(?<end>(\d+|))"); start = long.Parse(m.Groups["start"].Value); end = long.Parse(m.Groups["end"].Value); } //Content-Length FileInfo info = new FileInfo(r.FilePath); long length = info.Length; if (start > length) start = 0; response.ContentLength64 = length - start; //Content-Range response.Headers["Content-Range"] = "bytes " + start.ToString() + "-" + (length - 1).ToString() + "/" + response.ContentLength64.ToString(); int t = 0; int limitcount = 0; int privateTick = 0; byte[] buf = new byte[1024]; //open output stream using (var fs = File.OpenRead(r.FilePath)) { fs.Position = start; using (var net = response.OutputStream) { using (var bs = new BufferedStream(net, r.BufferSize)) { while (true) { int read = 0; if (r.SpeedLimit > 0) { limitcount++; read = fs.Read(buf, 0, buf.Length); if (limitcount >= r.SpeedLimit) { t = System.Environment.TickCount - privateTick; if (t < 1000) Thread.Sleep(1000 - t); limitcount = 0; privateTick = System.Environment.TickCount; } } else { read = fs.Read(buf, 0, buf.Length); } if (read <= 0) break; bs.Write(buf, 0, read); } } //bs.Flush(); } }//end write return ActionResult.Handled; }
public static ActionResult SendFile(this HttpListenerResponse response, FileResponse r) { response.StatusCode = 200; //content-type response.ContentType = r.ContentType; //Range response.Headers["Accept-Ranges"] = "bytes"; long start = r.Start; long end = 0; if (!string.IsNullOrEmpty(r.Range)) { Match m = Regex.Match(r.Range, @"(?<start>\d+)\-(?<end>(\d+|))"); start = long.Parse(m.Groups["start"].Value); end = long.Parse(m.Groups["end"].Value); } //Content-Length FileInfo info = new FileInfo(r.FilePath); long length = info.Length; if (start > length) { start = 0; } response.ContentLength64 = length - start; //Content-Range response.Headers["Content-Range"] = "bytes " + start.ToString() + "-" + (length - 1).ToString() + "/" + response.ContentLength64.ToString(); int t = 0; int limitcount = 0; int privateTick = 0; byte[] buf = new byte[1024]; //open output stream using (var fs = File.OpenRead(r.FilePath)) { fs.Position = start; using (var net = response.OutputStream) { using (var bs = new BufferedStream(net, r.BufferSize)) { while (true) { int read = 0; if (r.SpeedLimit > 0) { limitcount++; read = fs.Read(buf, 0, buf.Length); if (limitcount >= r.SpeedLimit) { t = System.Environment.TickCount - privateTick; if (t < 1000) { Thread.Sleep(1000 - t); } limitcount = 0; privateTick = System.Environment.TickCount; } } else { read = fs.Read(buf, 0, buf.Length); } if (read <= 0) { break; } bs.Write(buf, 0, read); } } //bs.Flush(); } } //end write return(ActionResult.Handled); }