Sunday, April 17, 2011

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.

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...