c# WebClient文件下载

时间:2022-08-28 14:04:11
 public void HttpDownload(string url, string path, ResourceType type)
{
using (var client = new WebClient())
{
client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
var stream = client.OpenRead(url);
if (type == ResourceType.Document)
{
var header = client.ResponseHeaders["Content-Disposition"];
var subStr = header.Split('=');
var fileName = System.Web.HttpUtility.UrlDecode(subStr[1]);
path = GetFileValidation(path, fileName, out fileName);
}
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
ReadWriteStream(stream, writeStream);
}
}
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
//验证文件是否存在
public string GetFileValidation(string path, string oldTitle, out string newTitle)
{
string newPath = System.IO.Path.Combine(path, oldTitle.Replace("\"", ""));
string title1 = oldTitle; if (File.Exists(newPath))
{
for (int i = 1; i < int.MaxValue; i++)
{
newPath = System.IO.Path.Combine(path, oldTitle.Split('.')[0] + "(" + i + ")" + "." + oldTitle.Split('.')[1]);
if (!File.Exists(newPath))
{
title1 = oldTitle.Split('.')[0] + "(" + i + ")" + "." + oldTitle.Split('.')[1];
break;
}
else
{
continue;
}
}
}
newTitle = title1;
return newPath;
}