一個ASP.NET檔案下載類

來源:互聯網
上載者:User

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

    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.