views:

1285

answers:

3

In C#.NET, I want to fetch data from an URL and save it to a file in binary.

Using HttpWebRequest/Streamreader to read into a string and saving using StreamWriter works fine with ASCII, but non-ASCII characters get mangled because the Systems thinks it has to worry about Encodings, encode to Unicode or from or whatever.

What is the easiest way to GET data from an URL and saving it to a file, binary, as-is?

                // This code works, but for ASCII only
                String url = "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();
          StreamReader readStream = new StreamReader( ReceiveStream );
          string contents = readStream.ReadToEnd();

          string filename = @"...";

             // create a writer and open the file
          TextWriter tw = new StreamWriter(filename);
          tw.Write(contents.Substring(5));
          tw.Close();
A: 

Just don't use any StreamReader or TextWriter. Save 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);
Matthew Flaschen
+3  A: 

Minimalist answer:

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

Less to get wrong...

Marc Gravell
Perfect just what I needed thank you!
jms
Would be good if it could download gzipped files?
Greg
Wouldn't it just.
Marc Gravell
A: 

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");
Aviatrix