Alex G
Alex G

Reputation: 2309

Create directory programmatically

I want to create a directory inside my applicationSupportDirectory. My understanding is that the applicationSupportDirectory does not allow users to see the data within. This is why I have chosen it. However, the code I am using below seems to fail and I am not sure why.

Can anyone tell me what I have done wrong? Thanks!

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0]; // Get directory
NSString *dataPath = [applicationDirectory stringByAppendingPathComponent:@"drawings"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){

NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
  ;// success
else
{
  NSLog(@"Failed");
}
}
}

Upvotes: 6

Views: 2436

Answers (3)

dhaya
dhaya

Reputation: 1522

Try this one, it works for me.

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                              NSUserDomainMask,
                                                              YES)[0];
NSString *folder = [documentsPath stringByAppendingPathComponent:@"foldername"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]){
    [fileManager createDirectoryAtPath:folder
           withIntermediateDirectories:YES
                            attributes:nil
                                 error:&error];
}

Upvotes: 6

kamalesh kumar yadav
kamalesh kumar yadav

Reputation: 966

To create Dirtectory

NSError *error;
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/directoryname"];
NSLog(@"%@",path);
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
    // Set do not backup attribute to whole folder

}

Upvotes: -1

Gaurav Rastogi
Gaurav Rastogi

Reputation: 2145

NSString *directoryName = @"drawing";

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,   NSUserDomainMask, YES);

NSString *applicationDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
NSError *error;

if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
                               withIntermediateDirectories:YES
                                                attributes:nil
                                                     error:&error])
{
    NSLog(@"Create directory error: %@", error);
}

Hope it will help you

Upvotes: 5

Related Questions