Removing non-empty folders and specific file types

  • What is the best way to delete a folder by deleting all subfolders and files?
  • What is the best way to delete files with a specific extension; for example, if I only want to delete files with the extension '.txt'?

Cocoa or carbon.

+2


source to share


3 answers


To delete a directory tree (or file) use -[NSFileManager removeItemAtPath:error:]

. This removes files directly (and deletes all of them ); if you want to move an item to the cart instead use NSWorkspaceRecycleOperation

.

How to delete only files with certain extensions: Get each path pathExtension

and use caseInsensitiveCompare:

to compare it to the ones you are looking for, then delete the file if it is on your hit list.



If you want to merge the two (that is, delete only files in the directory tree that have a given extension), you will need to get the directory enumerator from NSFileManager and traverse the directory tree yourself, deleting the files one at a time.

+3


source


Yes, be sure to use the trash bin, unless, of course, these are files that the user should not see / know.



+1


source


To delete files with a specific extension ..

At least one way. This example simply searches the application documents directory for any jpg files and removes them.

    NSFileManager *fManager = [NSFileManager defaultManager];
    NSString *dir = [self applicationDocumentsDirectory];

    NSError *error;
    NSArray *files = [fManager contentsOfDirectoryAtPath:dir error:&error];

    for (NSString *file in files) {

          if ([[[file pathExtension] lowercaseString] isEqualToString: @"jpg"]) 
          {
              [fManager removeItemAtPath: [dirstringByAppendingPathComponent:file] error:&error];
              NSLog(@"removed: %@",file);
          }

          if (error) {
             //deal with it
          }
     }

      

+1


source







All Articles