首页 > 其他分享 >删除指定天数前的所有文件夹

删除指定天数前的所有文件夹

时间:2023-01-10 10:36:35浏览次数:34  
标签:删除 天数 DateTime DirectoryInfo 文件夹 child dir

转载并整理于https://ask.csdn.net/questions/7488035

/// <summary>
        /// 删除指定天数前的所有文件夹
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="time">天数</param>
        public static void DeleteFolder(string path, int time)
        {
            DirectoryInfo dir = new DirectoryInfo(path);
            if (dir.Exists)
            {
                DirectoryInfo[] childs = dir.GetDirectories();
                foreach (DirectoryInfo child in childs)
                {
                    //文件夹名转为时间格式
                    DateTime dt2 = DateTime.ParseExact(child.Name, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

                    //时间差
                    TimeSpan ts = DateTime.Now - dt2;
                    if (ts.Days >= time)
                        child.Delete(true);
                }
            }
        }

用法:

 DeleteFolder(AppDomain.CurrentDomain.BaseDirectory + "Images\\", 2);//2的意思:当天是10号,那么删除的就是9号之前的文件夹(。。。5,6,7,8)

标签:删除,天数,DateTime,DirectoryInfo,文件夹,child,dir
From: https://www.cnblogs.com/yuanqi99977/p/17039358.html

相关文章