首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASMX文件下载

ASMX文件下载
EN

Stack Overflow用户
提问于 2011-01-25 05:01:50
回答 1查看 8.4K关注 0票数 4

我有一个ASMX(无WCF) WCF服务,它有一个响应文件的方法,如下所示:

代码语言:javascript
复制
[WebMethod]
public void GetFile(string filename)
{
    var response = Context.Response;
    response.ContentType = "application/octet-stream";
    response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    using (FileStream fs = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath("~/"), fileName), FileMode.Open))
    {
        Byte[] buffer = new Byte[256];
        Int32 readed = 0;

        while ((readed = fs.Read(buffer, 0, buffer.Length)) > 0)
        {
            response.OutputStream.Write(buffer, 0, readed);
            response.Flush();
        }
    }
}

我想在控制台应用程序中使用web引用将此文件下载到本地文件系统。如何获取文件流?

另外,我尝试过通过post请求(使用HttpWebRequest类)下载文件,但我认为还有更好的解决方案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-01-25 05:08:16

您可以在web服务的web.config中启用HTTP。

代码语言:javascript
复制
    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>

然后,您应该能够只使用web客户端来下载文件(使用文本文件进行测试):

代码语言:javascript
复制
string fileName = "bar.txt"
string url = "http://localhost/Foo.asmx/GetFile?filename="+fileName;
using(WebClient wc = new WebClient())
wc.DownloadFile(url, @"C:\bar.txt");

编辑:

要支持设置和检索cookies,您需要编写一个覆盖GetWebRequest()的自定义WebClient类,这很容易做到,只需几行代码:

代码语言:javascript
复制
public class CookieMonsterWebClient : WebClient
{
    public CookieContainer Cookies { get; set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
        request.CookieContainer = Cookies;
        return request;
    }
}

要使用此自定义web客户端,您需要执行以下操作:

代码语言:javascript
复制
myCookieContainer = ... // your cookies

using(CookieMonsterWebClient wc = new CookieMonsterWebClient())
{
    wc.Cookies = myCookieContainer; //yum yum
    wc.DownloadFile(url, @"C:\bar.txt");
}
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4787122

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档