string filePath = FilesDown(url); //调用方法
#region 文件下载核心代码
private string FilesDown(string Url)
{
string pathFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Files/";
//判断文件夹是否存在
if (!Directory.Exists(pathFile))
{
Directory.CreateDirectory(pathFile);
}
pathFile += $@"{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.png";
WriteBytesToFile(pathFile, GetBytesFromUrl(Url));
return pathFile;
}
private byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();
Stream stream = myResp.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}
private 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();
}
}
#endregion
C#通过网络地址,将文件下载到本地
于 2023-03-25 13:08:07 首次发布