递归删除文件夹及文件的方法

 #region 递归删除文件夹及文件的方法
        /// <summary>
        /// 删除文件夹中所有文件夹和文件
        /// </summary>
        /// <param name="dirName"></param>
        public void deleteField(DirectoryInfo dirs)
        {

            //方法一:
            //foreach (var fileName in dirs.GetFiles())
            //{
            //    File.Delete(fileName.FullName);
            //}
            //foreach (var dir in dirs.GetDirectories())
            //{
            //    foreach (var fileName in dir.GetFiles())
            //    {
            //        File.Delete(fileName.FullName);
            //    }
            //    deleteField(dir.FullName);
            //    Directory.Delete(dir.FullName);
            //}

            //方法二:
            foreach (var item in dirs.GetFileSystemInfos())
            {
                if (File.Exists(item.FullName))
                {
                    File.Delete(item.FullName);
                }
                if (Directory.Exists(item.FullName))
                {
                    DirectoryInfo dirName = new DirectoryInfo(item.FullName);
                    deleteField(dirName);
                    Directory.Delete(item.FullName);
                }
            }
        }
        #endregion

posted @ 2012-03-22 20:09  欢喜王子  阅读(277)  评论(0编辑  收藏  举报