Save Image From URL

  • Thread starter Thread starter Josh Turpen
  • Start date Start date
J

Josh Turpen

Hey all I'm pretty new to .NET so this question may seem relatively
ignorant.
My question is that I have an Image Web Form object on my page that is
displaying an image from a URL.
I am having trouble figuring out how to convert it and saving it to disk.

Any directions/suggestions would be greatly appreciated. Thanks
 
Hi, Josh!

Use this code to get the array of bytes of the image.

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;
}

And use the following code to save it to disk.

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 this helps.

Sam
 
Back
Top