1. 程式人生 > >C# .NET 根據Url鏈接保存Image圖片到本地磁盤

C# .NET 根據Url鏈接保存Image圖片到本地磁盤

blank mar 取圖 查看 本地 文件 content C# 文件中

原文:C# .NET 根據Url鏈接保存Image圖片到本地磁盤

根據一個Image的Url鏈接可以在瀏覽器中顯示一個圖片,如果要通過代碼將圖片保存在本地磁盤可以通過以下方式:

1、首先獲取圖片的二進制數組。

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;

}

2、保存到磁盤文件中.

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

}

C# .NET 根據Url鏈接保存Image圖片到本地磁盤