我有一个ASMX(无WCF) WCF服务,它有一个响应文件的方法,如下所示:
[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类)下载文件,但我认为还有更好的解决方案。
发布于 2011-01-25 05:08:16
您可以在web服务的web.config中启用HTTP。
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>然后,您应该能够只使用web客户端来下载文件(使用文本文件进行测试):
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类,这很容易做到,只需几行代码:
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客户端,您需要执行以下操作:
myCookieContainer = ... // your cookies
using(CookieMonsterWebClient wc = new CookieMonsterWebClient())
{
wc.Cookies = myCookieContainer; //yum yum
wc.DownloadFile(url, @"C:\bar.txt");
}https://stackoverflow.com/questions/4787122
复制相似问题