How to save image from direct local URL to File

In my recent project its an requirement to save images from URL to hard disk or any media. After binged I have got several solutions. Now sharing you the right solution which is work for me.

Code(C#):

protected void Page_Load(object sender, EventArgs e)
{
string url = "http://img510.imageshack.us/img510/5523/aspnet4jh.jpg";
string DestinationPath ="C:/temp";
string filename = url.Substring(url.LastIndexOf('/')+1);
byte[] bytes=GetBytesFromUrl(url);
WriteBytesToFile(DestinationPath +"/"+filename, bytes);
}

static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();

Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}

static public void WriteBytesToFile(string fileName, byte[] content)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write(content);
}
finally
{
fs.Close();
w.Close();
}
}

Hope that it may help other guys. Thanks.

Comments

Popular posts from this blog

The model backing the 'MyDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.

"This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."

Check/Uncheck all items in a CheckBoxList using Javascript