Download image given a url in C# using the System.Net.HttpWebRequest class

Saves image url object into the local machine


///
/// Saves the list of url object into the output directory
///

/// list of url path
/// root directory that will be used for saving

internal static void PhotoDownloader(ArrayList aList, string outputDir)
{
Image imageStream = null;
DateTime dt = DateTime.Now;
String newDir = String.Format("{0:yyyy_mm_dd}", dt);
Directory.CreateDirectory(outputDir + newDir);
int ctr = 1;
foreach (String filename in aList)
{
try
{
System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(filename);
httpWebRequest.AllowWriteStreamBuffering = true;
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
httpWebRequest.Timeout = 30000; //30 seconds
System.Net.WebResponse webResponse = httpWebRequest.GetResponse();
System.IO.Stream webStream = webResponse.GetResponseStream();
imageStream = Image.FromStream(webStream);
webResponse.Close();
webResponse.Close();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.WriteLine((ctr++) + "Saving..." + filename);

String newFile = filename.Substring(filename.LastIndexOf("/") + 1);
imageStream.Save(outputDir + newDir + "/" + newFile);
}
}


You may ask, how can I do the same in java? Here's how:
http://czetsuya-tech.blogspot.com/2010/03/download-url-file-into-desktop-for.html
Download image given a url in C# using the System.Net.HttpWebRequest class Download image given a url in C# using the System.Net.HttpWebRequest class Reviewed by Edward Legaspi on Saturday, March 20, 2010 Rating: 5

No comments:

Powered by Blogger.