#region test
string fullFilePath = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
DownloadFile(fullFilePath);
DownloadFile2(fullFilePath);
#endregion
#region 下载1
public static bool DownloadFile(string fullFilePath)
{
try
{
string basePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "temp");
if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
string extension = Path.GetExtension(fullFilePath);
Random random = new Random();
string fileName = DateTime.Now.ToString("yyyyMMddHHmm") + Guid.NewGuid().ToString().Replace("-", "").Substring(9, 16) + random.Next(100000, 999999) + extension;
string saveFilePath = Path.Combine(basePath, fileName);
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(fullFilePath, saveFilePath);
}
if (File.Exists(saveFilePath))
return true;
return false;
}
catch
{
return false;
}
}
#endregion
#region 下载2
public static bool DownloadFile2(string fullFilePath)
{
bool flag = false;
try
{
string basePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "temp");
if (!Directory.Exists(basePath))
Directory.CreateDirectory(basePath);
string extension = Path.GetExtension(fullFilePath);
Random random = new Random();
string fileName = DateTime.Now.ToString("yyyyMMddHHmm") + Guid.NewGuid().ToString().Replace("-", "").Substring(9, 16) + random.Next(100000, 999999) + extension;
string saveFilePath = Path.Combine(basePath, fileName);
using (FileStream fileStream = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write))
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullFilePath);
//接收响应
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//输出流
Stream responseStream = response.GetResponseStream();
byte[] bufferBytes = new byte[10000];//缓冲字节数组
int bytesRead = -1;
while ((bytesRead = responseStream.Read(bufferBytes, 0, bufferBytes.Length)) > 0)
{
fileStream.Write(bufferBytes, 0, bytesRead);
}
if (fileStream.Length > 0)
{
flag = true;
}
//关闭写入
fileStream.Flush();
fileStream.Close();
}
return flag;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion