[ACCEPTED]-How to GET data from an URL and save it into a file in binary in C#.NET without the encoding mess?-binary

Accepted answer
Score: 57

Minimalist answer:

using (WebClient client = new WebClient()) {
    client.DownloadFile(url, filePath);
}

Or in PowerShell (suggested 1 in an anonymous edit):

[System.Net.WebClient]::WebClient
$client = New-Object System.Net.WebClient
$client.DownloadFile($URL, $Filename)
Score: 15

Just don't use any StreamReader or TextWriter. Save 1 into a file with a raw FileStream.

String url = ...;
HttpWebRequest  request  = (HttpWebRequest) WebRequest.Create(url);

// execute the request
HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// we will read data via the response stream
Stream ReceiveStream = response.GetResponseStream();

string filename = ...;

byte[] buffer = new byte[1024];
FileStream outFile = new FileStream(filename, FileMode.Create);

int bytesRead;
while((bytesRead = ReceiveStream.Read(buffer, 0, buffer.Length)) != 0)
    outFile.Write(buffer, 0, bytesRead);

// Or using statement instead
outFile.Close()
Score: 0

This is what I use:

sUrl = "http://your.com/xml.file.xml";
rssReader = new XmlTextReader(sUrl.ToString());
rssDoc = new XmlDocument();

WebRequest wrGETURL;
wrGETURL = WebRequest.Create(sUrl);

Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream, Encoding.UTF8);
WebResponse wr = wrGETURL.GetResponse();
Stream receiveStream = wr.GetResponseStream();
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
string content = reader.ReadToEnd();
XmlDocument content2 = new XmlDocument();

content2.LoadXml(content);
content2.Save("direct.xml");

0

More Related questions