在库文件c#发送httpresponses(sending httpresponses in lib

2019-10-17 07:03发布

我用下面的代码来下载文件夹在asp.net网站的

 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;
    }
}

它工作正常/ ...

但我的问题是,当我使用相同的代码库文件

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;
                }
            }
        }

它抛出了我一个错误的

当使用自定义的TextWriter的OutputStream不可用。

我想这个问题是在该行

 HttpResponse Response = new HttpResponse(TextWriter.Null);

你能提供给我一个解决方案

等待您的答复....

Answer 1:

您可以使用此代码尝试

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


Answer 2:

我取代了的结构如

   HttpResponse response = HttpContext.Current.Response;

它工作正常.....

感谢大家的支持



文章来源: sending httpresponses in library file c#