1. 文件下载与目录

public class ManageDownloadFile
{
    #region 判断文件夹是否可以删除
    public static bool ParseDeleteDir(string dirPath)
    {
        return (!string.IsNullOrEmpty(dirPath) && Directory.Exists(dirPath)
            && (Directory.GetFiles(dirPath) != null && Directory.GetFiles(dirPath).Length > 0));
    }
    #endregion

    #region 文件(目錄)分析
    private static void ParseFileDir(string path, bool isDelDir = false)
    {
        //如果已經存在目標文件時,則設置目標文件的可讀寫狀態
        if (File.Exists(path))
            File.SetAttributes(path, FileAttributes.Normal);
        else
        {
            //創建父級目錄
            string dirPath = Path.GetDirectoryName(path);
            bool isExistsFile = ParseDeleteDir(dirPath);

            if (isDelDir && isExistsFile)
                Directory.Delete(dirPath);
            else if (!isDelDir && !isExistsFile)
                Directory.CreateDirectory(dirPath);
        }
    }
    #endregion

    #region 字符串转string列表
    public static List<string> ToListStr(string str, char tag = ',')
    {
        if (!string.IsNullOrEmpty(str))
            return new List<string>(str.Split(tag));
        else
            return null;
    }
    #endregion

    #region 复制文件
    public static bool CopyFile(string sourcePath, string savePath)
    {
        if (!string.IsNullOrEmpty(sourcePath) && !string.IsNullOrEmpty(savePath) && File.Exists(sourcePath))
        {
            ParseFileDir(savePath);

            //複製文件
            if (File.Exists(sourcePath))
                File.Copy(sourcePath, savePath, true);

            return true;
        }
        return false;
    }
    #endregion

    #region 文件下載
    /// <summary>
    /// 文件流下載
    /// </summary>
    /// <param name="url">網絡文件請求地址</param>
    /// <param name="savePath">保存文件到本地路徑(例如:E:\QpDesignAttachFiles\UserPhoto\temp\thumb\A486E5AA9C5D5EACAEFF439A0CD1C068.PNG)</param>
    /// <returns></returns>
    public static bool DownloadFile(string url, string savePath)
    {
        bool bSucceed = false;

        if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(savePath))
        {
            //Http請求
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            try
            {
                request = WebRequest.Create(url) as HttpWebRequest;

                if (request != null)
                {
                    request.Method = "GET";
                    request.KeepAlive = true;
                    request.Timeout = 30000;

                    response = request.GetResponse() as HttpWebResponse;

                    if (response != null && response.ContentType.IndexOf("html") == -1)
                    {
                        //获取到文件流后,创建文件目录
                        ParseFileDir(savePath);

                        using (FileStream streamWrite = File.Open(savePath, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            //文件存在,則覆蓋
                            streamWrite.SetLength(0);

                            using (Stream streamRead = response.GetResponseStream())
                            {
                                byte[] readBuff = new byte[1024 * 128];
                                int count = streamRead.Read(readBuff, 0, readBuff.Length);

                                while (count > 0)
                                {
                                    streamWrite.Write(readBuff, 0, count);
                                    count = streamRead.Read(readBuff, 0, readBuff.Length);
                                }

                                bSucceed = true;
                            }
                        }
                    }
                }
            }
            catch (Exception Err)
            {
                System.Web.HttpContext.Current.Response.Write(Err);
            }
            finally
            {
                if (response != null)
                    response.Close();
                if (request != null)
                    request.Abort();
            }
        }

        return bSucceed;
    }
    
    public static void DownloadWebFile(string url, string savePath)
    {
        new System.Net.WebClient().DownloadFile(url, savePath);
    }
    #endregion
}
View Code

2. 自定义下载类

public class WebsiteLoadInfo
{
    private string _WebCode;
    private string _WebSite;
    private string _DownloadSite;
    private string _SaveDir;

    public WebsiteLoadInfo() { }

    public WebsiteLoadInfo(string webCode, string dir)
    {
        _WebCode = webCode;
        _SaveDir = dir;
    }

    public string WebCode
    {
        get { return _WebCode; }
        set { _WebCode = value; }
    }

    public string WebSite
    {
        get{ return _WebSite; }
        set { _WebSite = value; }
    }

    public string DownloadSite
    {
        get{ return _DownloadSite; }
        set { _DownloadSite = value; }
    }

    public string SaveDir
    {
        get
        {
            string dirPath = "";
            if (string.IsNullOrEmpty(_SaveDir))
                dirPath = System.Web.HttpContext.Current.Server.MapPath("~/AttachFiles");
            else
            {
                if (_SaveDir.IndexOf(@":/") > 0)
                    dirPath = _SaveDir;
                else if (_SaveDir.IndexOf(@"~/") > -1)
                    dirPath = System.Web.HttpContext.Current.Server.MapPath(_SaveDir);
                else
                    dirPath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/{0}", _SaveDir));
            }
            return dirPath;
            //return dirPath.Substring(0, dirPath.LastIndexOf("/AttachFiles") + 1);
        }
        set { _SaveDir = value; }
    }
}

/// <summary>
/// 文件下載信息
/// </summary>
public class FileDownloadInfo
{
    private string _Url;
    private string _SavePath;
    private bool _IsUpload;

    public FileDownloadInfo() { }

    public FileDownloadInfo(string url, string savePath)
    {
        _Url = url;
        _SavePath = savePath;
        _IsUpload = CreateDirFile.DownloadFile(_Url, _SavePath);
    }

    public FileDownloadInfo(WebsiteLoadInfo web, string path)
    {
        _Url = string.Format("{0}/{1}", web.WebSite, path);
        _SavePath = string.Format("{0}/{1}", web.SaveDir, path);
        _IsUpload = CreateDirFile.DownloadFile(_Url, _SavePath);
    }

    public string Url
    {
        get { return _Url; }
        set { _Url = value; }
    }

    public string SavePath
    {
        get { return _SavePath; }
        set { _SavePath = value; }
    }

    public bool IsUpload
    {
        get {
            if(!_IsUpload)
                _IsUpload = CreateDirFile.DownloadFile(_Url, _SavePath);

            return (_IsUpload && File.Exists(_SavePath));
        }
        //set { _IsUpload = value; }
    }
}
View Code

 

posted on 2020-11-25 16:25  欲穷  阅读(54)  评论(0编辑  收藏  举报