Download ASMX file

I have an ASMX web service (without WCF) with a method that responds to a file that looks like this:

[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 upload this file to the local file system using the web link in my console application. How to get a file?

PS I tried uploading files by mail (using the HttpWebRequest class), but I think there is a much more elegant solution.

+3
source share
1 answer

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

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

Then you can simply use the web client to download the file (tested by a 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:

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

-, :

myCookieContainer = ... // your cookies

using(CookieMonsterWebClient wc = new CookieMonsterWebClient())
{
    wc.Cookies = myCookieContainer; //yum yum
    wc.DownloadFile(url, @"C:\bar.txt");
}
+8

Source: https://habr.com/ru/post/1787547/


All Articles