Tuesday, July 12, 2005

Saving a web page to a file using C#

public static void HttpConnectionSaveToFile(string strUrl,string SavedPath)
{
System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
System.IO.Stream stream = webResponse.GetResponseStream();
System.IO.BinaryReader streamReader = new System.IO.BinaryReader(stream);
byte[] b = streamReader.ReadBytes((int)webResponse.ContentLength);
//-----release the reader and stream resource-----
if (System.IO.File.Exists(SavedPath))
{
//Console.WriteLine("{0} already exists!", SavedPath);
System.IO.File.Delete(SavedPath);
}
System.IO.FileStream fs = new System.IO.FileStream(SavedPath, System.IO.FileMode.CreateNew);
// Create the writer for data.
System.IO.BinaryWriter w = new System.IO.BinaryWriter(fs);
// Write data to Test.data.
w.Write( b );
w.Close();
fs.Close();

streamReader.Close();
stream.Close();
}

1 comment:

Tomáš Polák said...

Thanks for your contribution. Very helpfull for me.