2011-01-24 55 views
3

我有一個ASMX(不WCF)Web服務與方法的反應,看起來像一個文件:ASMX文件下載

[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(); 
     } 
    } 
} 

,我想利用網絡參考下載此文件下載到本地文件系統在我的控制檯應用程序。如何獲取文件流?

P.S.我通過post request(使用HttpWebRequest類)嘗試下載文件,但我認爲有更多更優雅的解決方案。

回答

8

你可以在你的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"); 

編輯:

支持設置和獲取餅乾你需要寫一個自定義的WebClient類中的覆蓋GetWebRequest(),這是很容易做到,代碼只需要幾行:

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"); 
} 
+0

感謝您的回答!有沒有辦法爲WebClient實例提供cookie(如CookieContainer屬性)?我使用cookies進行身份驗證。 – 2xMax 2011-01-24 21:17:16