C# 递归 删除文件夹及子文件夹内文件

时间:2022-09-03 19:37:23

 

/// <summary>
        /// 删除文件夹及子文件内文件
        /// </summary>
        /// <param name="str"></param>
        public void DeleteFiles(string str)
        {
             DirectoryInfo fatherFolder = new DirectoryInfo(str);
            //删除当前文件夹内文件
             FileInfo[] files = fatherFolder.GetFiles();
             foreach (FileInfo file in files)
             {
                 //string fileName = file.FullName.Substring((file.FullName.LastIndexOf("\\") + 1), file.FullName.Length - file.FullName.LastIndexOf("\\") - 1);
                 string fileName = file.Name;
                 try
                 {
                     if (!fileName.Equals("index.dat"))
                     {
                         File.Delete(file.FullName);
                     }                     
                 }
                 catch (Exception ex)
                 {
                 }
             }
            //递归删除子文件夹内文件
             foreach (DirectoryInfo childFolder in fatherFolder.GetDirectories())
             {
                DeleteFiles(childFolder.FullName);
             }
            
 
        }