Here's what I got so far (that doesn't work). At this point I thought my target was Ansi encoded, but I really don't want to have to know at this point. My browser seems to be able to determine what encoding to use, How can I?
static void GetUrl(Uri uri, string localFileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response;
response = (HttpWebResponse)request.GetResponse();
// Save the stream to file
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.Default);
Stream fileStream = File.OpenWrite(localFileName);
using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default))
{
sw.Write(reader.ReadToEnd());
sw.Flush();
sw.Close();
}
}
After answers (currently only tested on a UTF-8 site):
static void GetUrl(Uri uri, string localFileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
try
{
// Hope GetEncoding() knows how to parse the CharacterSet
Encoding encoding = Encoding.GetEncoding(response.CharacterSet);
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
using (StreamWriter sw = new StreamWriter(localFileName, false, encoding))
{
sw.Write(reader.ReadToEnd());
sw.Flush();
sw.Close();
}
}
finally
{
response.Close();
}
}