public static class FilesDownLoad
{
private static readonly Dictionary<string, string> MimeDic = new Dictionary<string, string>();
static FilesDownLoad()
{
MimeDic.Add("text/plain", "txt");
MimeDic.Add("image/jpeg", "jpg");
MimeDic.Add("image/gif", "gif");
}
/// <summary>
/// 下载文件到指定目录,并返回下载后存放的文件路径
/// </summary>
/// <param>网址</param>
/// <param>存放目录,如果该目录中已存在与待下载文件同名的文件,那么将自动重命名</param>
/// <returns>下载文件存放的文件路径</returns>
public static string DownLoadFile(Uri Uri, string savePath)
{
WebResponse q = WebRequest.Create(Uri).GetResponse();
Stream s = q.GetResponseStream();
var b = new BinaryReader(s);
string file = CreateSavePath(savePath, Uri, q.ContentType);
var fs = new FileStream(file, FileMode.Create, FileAccess.Write);
fs.Write(b.ReadBytes((int)q.ContentLength), 0, (int)q.ContentLength);
fs.Close();
b.Close();
s.Close();
return file;
}
private static string CreateSavePath(string SaveCategory, Uri Uri, string ContentType)
{
if (Directory.Exists(SaveCategory) == false)
Directory.CreateDirectory(SaveCategory);
string ex = GetExtentName(ContentType);
string up = null;
string upne = null;
if (Uri.LocalPath == "/")
{
//处理Url是域名的情况
up = upne = Uri.Host;
}
else
{
if (Uri.LocalPath.EndsWith("/"))
{
//处理Url是目录的情况
up = Uri.LocalPath.Substring(0, Uri.LocalPath.Length - 1);
upne = Path.GetFileName(up);
}
else
{
//处理常规Url
up = Uri.LocalPath;
upne = Path.GetFileNameWithoutExtension(up);
}
}
string name = string.IsNullOrEmpty(ex) ? Path.GetFileName(up) : upne + "." + ex;
string fn = Path.Combine(SaveCategory, name);
int x = 1;
while (File.Exists(fn))
{
fn = Path.Combine(SaveCategory,
Path.GetFileNameWithoutExtension(name) + "(" + x++ + ")" + Path.GetExtension(name));
}
return fn;
}
private static string GetExtentName(string ContentType)
{
foreach (string f in MimeDic.Keys)
{
if (ContentType.ToLower().IndexOf(f) >= 0) return MimeDic[f];
}
return null;
}
}
测试用法如下:
[TestFixture]
public class FileDownLoadTests
{
[Test]
[Ignore]
public void 测试下载()
{
string d = @"D:\MyTest\Downloads";
//首次下载
Assert.AreEqual(@"D:\MyTest\Downloads\cf697a340f684bc1a9018e98.jpg",
FilesDownLoad.DownLoadFile(new Uri("http://hiphotos.baidu.com/huyangdiy/pic/item/cf697a340f684bc1a9018e98.jpg"), d));
//第二次下载,遇到同名文件,自动重命名
Assert.AreEqual(@"D:\MyTest\Downloads\cf697a340f684bc1a9018e98(1).jpg",
FilesDownLoad.DownLoadFile(new Uri("http://hiphotos.baidu.com/huyangdiy/pic/item/cf697a340f684bc1a9018e98.jpg"), d));
}
}