Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASMX file download

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.

like image 293
2xMax Avatar asked Feb 26 '23 07:02

2xMax


1 Answers

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");
}
like image 99
BrokenGlass Avatar answered Mar 04 '23 23:03

BrokenGlass