Exemplo n.º 1
0
        public static void SaveFile(HttpListenerContext context, string fileName)
        {
            var response = context.Response;

            using (FileStream fs = File.OpenRead(fileName))
            {
                response.ContentLength64 = fs.Length;
                response.SendChunked     = false;
                response.ContentType     = HttpMime.GetMimeString(fileName);
                response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(fileName));

                byte[] buffer = new byte[64 * 1024];
                using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
                {
                    int read;
                    while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bw.Write(buffer, 0, read);
                    }

                    bw.Flush();
                    bw.Close();
                }

                response.StatusCode        = (int)HttpStatusCode.OK;
                response.StatusDescription = "OK";
                response.OutputStream.Close();
            }
        }
Exemplo n.º 2
0
        public static void WriteFile(HttpListenerContext context, string fileName)
        {
            using (Stream input = new FileStream(fileName, FileMode.Open))
            {
                context.Response.ContentType     = HttpMime.GetMimeString(fileName);
                context.Response.ContentLength64 = input.Length;
                context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(fileName).ToString("r"));

                int    nbytes;
                byte[] buffer = new byte[1024 * 32];
                while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, nbytes);
                }
                input.Close();
                context.Response.OutputStream.Flush();
                context.Response.OutputStream.Close();

                context.Response.StatusCode = (int)HttpStatusCode.OK;
            }
        }