首页 > Windows开发 > 详细

[No000073]C#直接删除指定目录下的所有文件及文件夹(保留目录)

时间:2015-12-30 13:02:27      阅读:282      评论:0      收藏:0      [点我收藏+]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 进制转换
{
    class Program
    {
        #region 直接删除指定目录下的所有文件及文件夹(保留目录)
        /// <summary>
        ///直接删除指定目录下的所有文件及文件夹(保留目录)
        /// </summary>
        /// <param name="strPath">文件夹路径</param>
        /// <returns>执行结果</returns>
        public static bool DeleteDir(string strPath)
        {
            try
            {
                strPath = @strPath.Trim().ToString();// 清除空格
                if (System.IO.Directory.Exists(strPath))// 判断文件夹是否存在
                {
                    string[] strDirs = System.IO.Directory.GetDirectories(strPath);// 获得文件夹数组
                    string[] strFiles = System.IO.Directory.GetFiles(strPath);// 获得文件数组
                    foreach (string strFile in strFiles)// 遍历所有子文件夹
                    {
                        System.Diagnostics.Debug.Write(strFile+"-deleted");
                        System.IO.File.Delete(strFile);// 删除文件夹
                    }
                    foreach (string strdir in strDirs)// 遍历所有文件
                    {
                        System.Diagnostics.Debug.Write(strdir + "-deleted");
                        System.IO.Directory.Delete(strdir, true);// 删除文件
                    }
                }
                return true;// 成功
            }
            catch (Exception Exp) // 异常处理
            {
                System.Diagnostics.Debug.Write(Exp.Message.ToString());// 异常信息
                return false;// 失败
            }
        }
        #endregion
        static void Main(string[] args)
        {
            DeleteDir(@"C:\Users\HK\AppData\Local\Temp");
            Console.ReadKey();
        }

    }
}

注:无法删除被占用的文件!

[No000073]C#直接删除指定目录下的所有文件及文件夹(保留目录)

原文:http://www.cnblogs.com/Chary/p/No000073.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!