How to Download a File from a Website in C#

How to download a file from a website in C#

With the WebClient class:

using System.Net;
//...
WebClient Client = new WebClient ();
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png");

How to download a file from an URL to a server folder

can use System.Net.WebClient

using (WebClient Client = new WebClient ())
{
Client.DownloadFile (
// Param1 = Link of file
new System.Uri("Given URL"),
// Param2 = Path to save
"On SERVER PATH"
);
}

How to download a file from a URL using c#

Lasse Vågsæther Karlsen is correct. Your browser is smart enough to decompress the file because the response contains the header:

content-encoding:"gzip"

You can download and decompress the file with this code (adjust accordingly for your file name, path, etc.)

void Main()
{
using (var client = new WebClient())
{
client.Headers.Add("accept", "*/*");
byte[] filedata = client.DownloadData("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=1396-08-08");

using (MemoryStream ms = new MemoryStream(filedata))
{
using (FileStream decompressedFileStream = File.Create("c:\\deleteme\\test.xlsx"))
{
using (GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress))
{
decompressionStream.CopyTo(decompressedFileStream);
}
}
}
}
}

Downloading a file from a website using C#

I tested that URL with wget, and got a 403 error. I was able to solve that problem by adding a user-agent string to the header

Try adding a user-agent string to the header, using webClient.Headers.Add(HttpRequestHeader.UserAgent, "blah")

Download a file from website, without specific file url

Try this approach:

var client = new HttpClient
{
BaseAddress = new Uri("https://thunderstore.io/")
};

var response = await client.GetStreamAsync("package/download/Raus/IonUtility/1.0.1/");

var fn = Path.GetTempFileName();

using (var file = File.OpenWrite(fn))
{
await response.CopyToAsync(file);
}

At the end fn will hold the local file name. There is no dialog and you have the full control.

C# Download file from URL

Looking in Fiddler the request fails if there is not a legitimate U/A string, so:

WebClient wb = new WebClient();
wb.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.33 Safari/537.36");
wb.DownloadFile("http://www.cryptopro.ru/products/cades/plugin/get_2_0/cadeplugin.exe", "c:\\xxx\\xxx.exe");

How to Download a file from a website programatically c#

You'll need to post your data to the server with your client request as explained by @Peter.

This is an ASP.net page, and therefore it requires that you send some data on postback in order to complete the callback.

Using google, I was able to find this as a proof of concept.

The following is a snippet I wrote in Linqpad to test it out. Here it is:

void Main()
{

WebClient webClient = new WebClient();

byte[] b = webClient.DownloadData("http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");

string s = System.Text.Encoding.UTF8.GetString(b);

var __EVENTVALIDATION = ExtractVariable(s, "__EVENTVALIDATION");

__EVENTVALIDATION.Dump();

var forms = new NameValueCollection();

forms["__EVENTTARGET"] = "btnLink_Excel";
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "11%2F15%2F2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;

webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");

var responseData = webClient.UploadValues(@"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(@"c:\11152011.csv", responseData);
}

private static string ExtractVariable(string s, string valueName)
{
string tokenStart = valueName + "\" value=\"";
string tokenEnd = "\" />";

int start = s.IndexOf(tokenStart) + tokenStart.Length;
int length = s.IndexOf(tokenEnd, start) - start;
return s.Substring(start, length);
}

C# download file from the web with login

This should do the job!

        CookieContainer cookieJar = new CookieContainer();
CookieAwareWebClient http = new CookieAwareWebClient(cookieJar);

string postData = "name=********&password=*********&submit=submit";
string response = http.UploadString("https://www.loginpage.com/", postData);

// validate your login!

http.DownloadFile("https://www.loginpage.com/export_excel.php?export_type=list", "my_excel.xls");

I have used CookieAwareWebClient

public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }

public CookieAwareWebClient()
: this(new CookieContainer())
{
}

public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = cookies;
}

protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
HttpWebRequest httpRequest = (HttpWebRequest)request;
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return httpRequest;
}

protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];

if (setCookieHeader != null)
{
//do something if needed to parse out the cookie.
if (setCookieHeader != null)
{
Cookie cookie = new Cookie(); //create cookie
this.CookieContainer.Add(cookie);
}
}
return response;
}
}

Source & Credit for : CookieAwareWebClient



Related Topics



Leave a reply



Submit