C solution for deleting file directories or files

  • 2020-05-12 03:09:59
  • OfStack


///  Delete files and directories 
public class Cleaner

{

   ///
   ///  Deletes the specified directory and all files in that directory 
   ///
   ///  The path to delete a file or directory 
  
   public static void Clean ( string dir )

{
   
       CleanFiles ( dir );// The first 1 Secondary delete file 
   
       CleanFiles ( dir );// The first 2 Subdelete directory 
  
   }


private static void CleanFiles( string dir)

{
  
       if ( !Directory.Exists ( dir ) ) 
   
      {
          File.Delete ( dir );
          return;
   
      }
   
      else

    {

      string[] dirs = Directory.GetDirectories ( dir );

     string[] files = Directory.GetFiles ( dir );


   if ( 0 != dirs.Length )
     
     {
       
      foreach ( string subDir in dirs )
         
      {
           
       if ( null == Directory.GetFiles( subDir ) )
            
       {
                         Directory.Delete( subDir );
                
        return;
            
       }
            
       else CleanFiles ( subDir );
        
      }
     
     }
   
     if ( 0 != files.Length )
          {
     
      foreach ( string file in files )
      
      {
       
       File.Delete ( file );
               }
    
     }
    
     else Directory.Delete( dir );
   
    }

   }
}

How to use it,1 sentence.Directory.Delete(path, true)
Some of you may think that this is annoying and pointless, but you need to use recursion. A few lines of code will do.
But I want to say, the nice thing about using recursion is that you can, you know, make a judgment in there, like if you just want to delete part of the condition file, you can change it by 1... Let's say you just want to delete the name and so on.aaa.txt. Absolutely,

foreach ( string subDir in dirs )
         
      {
           
       if ( null == Directory.GetFiles( subDir )   && subDir == "aaa.txt")
            
       {
                         Directory.Delete( subDir );
                
        return;
            
       }
            
       else CleanFiles ( subDir );
        
      }

Of course I'm just doing a simple example, but hopefully it works.

Related articles: