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