I have created a folder within the Documents folder in my application directory .
I wanted to rename that folder through code,but not able to understand how to do it.
Please help me out.
Have you tried?
NString *newDirectoryName = #"<new folder name>";
NSString *oldPath = #"<path to the old folder>";
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
if (error) {
NSLog(#"%#",error.localizedDescription);
// handle error
}
NSString *oldDirectoryPath = #"Type your old directory Path";
NSArray *tempArrayForContentsOfDirectory =[[NSFileManager defaultManager] contentsOfDirectoryAtPath:oldDirectoryPath error:nil];
NSString *newDirectoryPath = [[oldDirectoryPath stringByDeletingLastPathComponent]stringByAppendingPathComponent:newDirectoryname];
[[NSFileManager defaultManager] createDirectoryAtPath:newDirectoryPath attributes:nil];
for (int i = 0; i < [tempArrayForContentsOfDirectory count]; i++)
{
NSString *newFilePath = [newDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]];
NSString *oldFilePath = [oldDirectoryPath stringByAppendingPathComponent:[tempArrayForContentsOfDirectory objectAtIndex:i]];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldFilePath toPath:newFilePath error:&error];
if (error) {
// handle error
}
}
Using moveItemAtPath should work. Sometimes the directory isn't actually "renamed" but really moved to another place. In which case the target path directory structure needs to be created as well.
Here a code snippet i'm using that works well :
-(BOOL)renameDir:(NSString *)dirPath asDir:(NSString *)newDirPath cleanExisting:(BOOL)clean
{
NSError *error = nil;
NSFileManager *fm = [NSFileManager defaultManager];
if (clean && [fm fileExistsAtPath:newDirPath])
{
[fm removeItemAtPath:newDirPath error:&error];
if (error != nil)
{
NSLog(#"Error while renameDir %# as %# :\n%#",dirPath,newDirPath,error);
return NO;
}
}
//Make sure container directories exist
NSString *newDirContainer = [newDirPath stringByDeletingLastPathComponent];
if (![fm fileExistsAtPath:newDirContainer])
{
[fm createDirectoryAtPath:newDirContainer withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error==nil)
{
[fm moveItemAtPath:dirPath toPath:newDirPath error:&error];
}
if (error!=nil)
{
NSLog(#"error while moveItemAtPath : %#",error);
}
return (error==nil);
}
This always work
NSLog (#"Copying download file from %# to %#", aPath, bPath);
if ([[NSFileManager defaultManager] fileExistsAtPath: bPath]) {
[[NSFileManager defaultManager] removeItemAtPath: bPath
error: &error];
}
if (![[NSFileManager defaultManager] copyItemAtPath: aPath
toPath: bPath
error: &error]){}
if ([[NSFileManager defaultManager] removeItemAtPath: aPath
error: &error]) {}
This is good article for renaming, deleting and create files.
// For error information
NSError *error;
// Create file manager
NSFileManager *fileMgr = [NSFileManager defaultManager];
// Point to Document directory
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
// Rename the file, by moving the file
NSString *filePath2 = [documentsDirectory stringByAppendingPathComponent:#"file2.txt"];
// Attempt the move
if ([fileMgr moveItemAtPath:filePath toPath:filePath2 error:&error] != YES)
NSLog(#"Unable to move file: %#", [error localizedDescription]);
// Show contents of Documents directory
NSLog(#"Documents directory: %#",
[fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error]);
http://iosdevelopertips.com/data-file-management/iphone-file-system-creating-renaming-and-deleting-files.html
Related
i used code for remove Temporary Directory files when using device.
-(void) clearAllTempFiles {
NSString *path = NSTemporaryDirectory();
if ([path length] > 0)
{
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL deleted = [fileManager removeItemAtPath:path error:&error];
if (deleted != YES || error != nil)
{
}
else{
// Recreate the Documents directory
[fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
}
}
}
it's not working fine? this is right code for deleting files from Temporary Directory?
pls help me?
You can get the tmp directory name on your mac by using this in your code:
Code:
(void)cacheDirectory {
NSString *tempPath = NSTemporaryDirectory();
NSLog(#"Temp Value = %#", items);
}
Call the method from wherever you want.
This will return the tmp folder name, then in finder do (cmd-shift-G) and paste the response you got from the console window.
The following will clear the TMP directory used by the Simulator.
Code:
NSString *tempPath = NSTemporaryDirectory();
NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:tempPath];
NSArray *onlyJPGs = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"self ENDSWITH '.jpg'"]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (onlyJPGs) {
for (int i = 0; i < [onlyJPGs count]; i++) {
NSLog(#"Directory Count: %i", [onlyJPGs count]);
NSString *contentsOnly = [NSString stringWithFormat:#"%#%#", tempPath, [onlyJPGs objectAtIndex:i]];
[fileManager removeItemAtPath:contentsOnly error:nil];
}
The above code clears only JPGs from the directory, so if you want to clear anything else then amend it.
I found simple one
NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#%#", NSTemporaryDirectory(), file] error:NULL];
}
I have some code that copies all the directories from "/Documents" to "Library/Caches/". The code is as follows:
NSString *oldPath = [NSString stringWithFormat:#"%#/Documents/", NSHomeDirectory()];
NSString *newPath = [NSMutableString stringWithFormat:#"%#/Library/Caches/", NSHomeDirectory()];
NSError *error = nil;
// get the list of all files and directories
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if(error != nil)
{
NSLog(#"\n\n\n1. There was an error in the file operation: %#", [error localizedDescription]);
return;
}
for(NSString *file in fileList)
{
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(#"The path for the file is: %#", path);
BOOL isDir = NO;
BOOL dirExists = [fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if(isDir && dirExists)
{
//Move to the new location
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error != nil)
{
NSLog(#"\n\n\n2. There was an error in the file operation: %#", [error localizedDescription]);
}
else
{
[fileManager removeItemAtPath:path error:&error];
if(error != nil)
NSLog(#"\n\n\n3. There was an error in the file operation: %#", [error localizedDescription]);
}
}
}
The copy works fine. I can see all the directories copied to the new location.
The problem is that the empty directories still remain in the Documents folder. I read up on removeItemAtPath in the docs and it says there that the contents of the directory are deleted. Whether the actual directory itself is deleted or not has no mention.
Could someone tell me what could be going wrong in the code? Why do the empty directories still remain?
EDIT:
On the first pass, when the directories exist in Documents, but not in Library/Caches, removeItemAtPath does not throw an error. The empty directories still remain in Documents, though. On the second pass of the above code, it attempts to remove the empty directories and removeItemAtPath throws a cocoa error 516 which is basically file not found - this is weird, because I can still see those empty directories.
Also, I'm running this code on iPhone Simulator 4.3.2 and iPhone Simulator 5.0, and monitoring the directory structure on my Mac in /Users/Library/Application Support/iPhone Simulator/....
This may be happening because of the trailing "/" in "/Documents/". Try removing the trailing "/" from the first 2 lines, or use this:
NSString *oldPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *newPath = [NSString pathWithComponents:[NSArray arrayWithObjects:NSHomeDirectory() , #"Library", #"Caches", nil]];
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *fileList = [fileManager contentsOfDirectoryAtPath:oldPath error:&error];
if (error) {
NSLog(#"\n\n\n1. There was an error in the file operation: %#", [error localizedDescription]);
return;
}
for (NSString *file in fileList) {
NSString *path = [oldPath stringByAppendingPathComponent:file];
NSLog(#"The path for the file is: %#", path);
BOOL isDir = NO;
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
[fileManager copyItemAtPath:path toPath:[newPath stringByAppendingPathComponent:file] error:&error];
if(error) {
NSLog(#"\n\n\n2. There was an error in the file operation: %#", [error localizedDescription]);
} else {
[fileManager removeItemAtPath:path error:&error];
if (error) {
NSLog(#"\n\n\n3. There was an error in the file operation: %#", [error localizedDescription]);
}
}
}
}
I guess this is a beginner's problem, but I was trying to check if a directory exists in my Documents folder on the iPhone. I read the documentation and came up with this code which unfortunately crashed with EXC_BAD_ACCESS in the BOOL fileExists line:
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:YES];
if (fileExists)
{
NSLog(#"Folder already exists...");
}
}
I don't understand what I've done wrong? It looks all perfect to me and it certainly complies with the docs, not? Any revelations as to where I went wrong would be highly appreciated! Thanks.
UPDATED:
Still not working...
-(void)checkIfDirectoryAlreadyExists:(NSString *)name
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *path = [[self documentsDirectory] stringByAppendingPathComponent:name];
BOOL isDir;
BOOL fileExists = [fileManager fileExistsAtPath:path isDirectory:&isDir];
if (fileExists)
{
if (isDir) {
NSLog(#"Folder already exists...");
}
}
}
Take a look in the documentation for this method signature:
- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory
You need a pointer to a BOOL var as argument, not a BOOL itself. NSFileManager will record if the file is a directory or not in that variable. For example:
BOOL isDir;
BOOL exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if (exists) {
/* file exists */
if (isDir) {
/* file is a directory */
}
}
Just in case somebody needs a getter, that creates a folder in Documents, if it doesn't exist:
- (NSString *)folderPath
{
if (! _folderPath) {
NSString *folderName = #"YourFolderName";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [documentPaths objectAtIndex:0];
_folderPath = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
// if folder doesn't exist, create it
NSError *error = nil;
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDir;
if (! [fileManager fileExistsAtPath:_folderPath isDirectory:&isDir]) {
BOOL success = [fileManager createDirectoryAtPath:_folderPath withIntermediateDirectories:NO attributes:nil error:&error];
if (!success || error) {
NSLog(#"Error: %#", [error localizedDescription]);
}
NSAssert(success, #"Failed to create folder at path:%#", _folderPath);
}
}
return _folderPath;
}
I have a Utility singleton class that I use for things like this. Since I can’t update my database if it remains in Documents, I copy my .sqlite files from Documents to /Library/Private Documents using this code. The first method finds the Library. The second creates the Private Documents folder if it doesn’t exist and returns the location as a string. The second method uses the same file manager method that #wzboson used.
+ (NSString *)applicationLibraryDirectory {
return [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
}
+ (NSString *)applicationLibraryPrivateDocumentsDirectory {
NSError *error;
NSString *PrivateDocumentsDirectory = [[self applicationLibraryDirectory] stringByAppendingPathComponent:#"Private Documents"];
BOOL isDir;
if (! [[NSFileManager defaultManager] fileExistsAtPath:PrivateDocumentsDirectory isDirectory:&isDir]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:PrivateDocumentsDirectory
withIntermediateDirectories:NO
attributes:nil
error:&error]) {
NSLog(#"Create directory error: %#", error);
}
}
return PrivateDocumentsDirectory;
}
I use it like this in my persistent store coordinator initialization. The same principal applies to any files though.
NSString *libraryDirectory = [Utilities applicationLibraryPrivateDocumentsDirectory];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:sqliteName];
NSString *destinationPath = [libraryDirectory stringByAppendingPathComponent:sqliteName];
I have a image name (lets say #"image.jpg" ) and i would like to save it to a folder i have created in my Documents folder named "coffeeShops". How can i do so ?
NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *dir = #"coffeeShops";
NSString *destPath = [docs stringByAppendingPathComponent:dir];
// check if the destination directory exists, if not create it
BOOL isDirectory;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory];
if(!exists || !isDirectory) {
NSError *error = nil;
[[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
if(error != nil) {
// should do error checking here
NSLog(#"%#",[error localizedDescription]);
}
}
NSString *fileName = #"image.jpg";
NSString *path = [destPath stringByAppendingPathComponent:fileName];
[UIImageJPEGRepresentation(image) writeToFile:path atomically:YES];
I have a /Documents/Images folder , in that folder are several other folders named after years , in those folders i have images. I want to delete everything from the images folder ( including the folders and the images in these folders).
I tried several code snippets but none delete the folders
my method:
- (void) clearCache:(NSString *) folderName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName];
NSLog(#"Removing items at path: %#",directory);
NSError *error = nil;
BOOL succes = [fm removeItemAtPath:directory error:&error];
/*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
//BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#%#", directory, file] error:&error];
BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error];
if (!success || error) {
// it failed.
}
}*/
}
NSFileManager *fm = [NSFileManager defaultManager];
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:#"urDirectory/"];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#%#", directory, file] error:&error];
if (!success || error) {
// it failed.
}
}
Hope this helps
Your code ([fm removeItemAtPath:directory error:&error];) should do it. If it doesn't, inspect the error it returns. If there's no error, but you still see files/subfolders - file a bug report!
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html