4

I have an ASMX(no WCF) webservice with a method that responses a file that looks like:

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

and I want to download this file to local filesystem using web reference in my console application. How to get the filestream?

P.S. I tried download files via post request(using HttpWebRequest class) but I think there is much more elegant solution.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
2xMax
  • 1,639
  • 6
  • 21
  • 41

1 Answers1

8

You can enable HTTP in the web.config of your web service.

    <webServices>
        <protocols>
            <add name="HttpGet"/>
        </protocols>
    </webServices>

Then you should be able to just use a web client to download the file (tested with text file):

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

Edit:

To support setting and retrieving cookies you need to write a custom WebClient class that overrides GetWebRequest(), it's easy to do and just a few lines of code:

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

To use this custom web client you would do:

myCookieContainer = ... // your cookies

using(CookieMonsterWebClient wc = new CookieMonsterWebClient())
{
    wc.Cookies = myCookieContainer; //yum yum
    wc.DownloadFile(url, @"C:\bar.txt");
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Thanks for the answer! Is there a way to provide cookies to the WebClient instance(like CookieContainer property)? I use cookies for authentication. – 2xMax Jan 24 '11 at 21:17