sending httpresponses in library file c#

2019-07-28 15:03发布

问题:

i used the following code to download the file folder in asp.net website are

 string path = @"E:\sample.zip";
        FileInfo file = new FileInfo(path);
           int len = (int)file.Length, bytes;
             Response.ContentType = "text/html";  
          // Response.AddHeader "Content-Disposition", "attachment;filename=" + filename; 
             Response.AppendHeader("content-length", len.ToString());
           byte[] buffer = new byte[1024];

        using(Stream stream = File.OpenRead(path)) {
    while (len > 0 && (bytes =
        stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        Response.OutputStream.Write(buffer, 0, bytes);
        len -= bytes;
    }
}

it works fine/...

but my problem is when i used the same code to the library file as

FileInfo file = new FileInfo(ZipPath);
            int len = (int)file.Length, bytes;
            HttpResponse Response = new HttpResponse(TextWriter.Null);
            Response.ContentType = "text/html";
            Response.AppendHeader("content-length", len.ToString());
            byte[] buffer = new byte[1024];

            using (Stream stream = File.OpenRead(ZipPath))
            {
                while (len > 0 && (bytes =
                    stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Response.OutputStream.Write(buffer, 0, bytes);
                    len -= bytes;
                }
            }
        }

it throws me a error as

OutputStream is not available when a custom TextWriter is used.

i guess the problem is in that line

 HttpResponse Response = new HttpResponse(TextWriter.Null);

can you provide me a solution

waiting for your responses....

回答1:

You can try with this code

TextWriter sw = new StringWriter();
HttpResponse Response = new HttpResponse(sw);


回答2:

i replaced the structures as

   HttpResponse response = HttpContext.Current.Response;

it works fine.....

Thanks all for your support