Re: Insuring a path exists
Re: Insuring a path exists
- Subject: Re: Insuring a path exists
- From: David Sinclair <email@hidden>
- Date: Tue, 8 Jun 2004 20:55:45 -0700
On Jun 8, 2004, at 19:54, Mike O'Connor wrote:
I have a path like this:
NSString* thePath=@"/Library/Application
Support/MyApp/MySubfolder/file.typ"
I want to insure that folders MyApp and MySubfolder exist, so that
when I do a writeToFile: using that path, it will succeed.
Is there a call I can make to insure the path exists, creating the
folders if needed, or do I have to write some code going through the
components of the path and doing it myself? TIA!
Here are a couple of methods I use, via a category on NSString:
@implementation NSString (DSFilePathStringCategories)
/*
validatedDirectoryPath
Expands a tilde and/or symbolic link in the path, then checks that all
directories in the path already exist. If any don't, they are created.
The expanded path is returned.
Written by DJS 2004-03.
*/
- (NSString *)validatedDirectoryPath
{
NSString *standardized = [self stringByStandardizingPath];
NSArray *components = [standardized pathComponents];
NSEnumerator *enumerator = [components objectEnumerator];
NSString *component;
NSString *path = @"";
while ((component = [enumerator nextObject]))
{
path = [path stringByAppendingPathComponent:component];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
[[NSFileManager defaultManager] createDirectoryAtPath:path
attributes:nil];
}
return path;
}
/*
validatedFilePath
Similar to -validatedDirectoryPath, above, except the last path
component is assumed to be a filename, and so is ignored.
Written by DJS 2004-03.
*/
- (NSString *)validatedFilePath
{
NSString *filename = [self lastPathComponent];
NSString *directory = [self stringByDeletingLastPathComponent];
directory = [directory validatedDirectoryPath];
NSString *path = [directory
stringByAppendingPathComponent:filename];
return path;
}
@end
--
David Sinclair, Dejal Systems, LLC - email@hidden
Custom Mac OS X development -
http://www.dejal.com/consulting/
Site change and failure monitor tool -
http://www.dejal.com/simon/
Plus other useful Mac products -
http://www.dejal.com/products/
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.