From dcdd0a6b9dd96c8189c0fca323500d5dd9be9f4f Mon Sep 17 00:00:00 2001 From: Martin Bektchiev Date: Tue, 5 Apr 2016 17:16:18 +0300 Subject: [PATCH] Ensure parent directory when creating a new file createNewFile throws an exception if the parent directory doesn't exist --- apps/tests/file-system-tests.ts | 10 ++++++++++ file-system/file-system-access.android.ts | 1 + file-system/file-system-access.ios.ts | 9 +++++---- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/apps/tests/file-system-tests.ts b/apps/tests/file-system-tests.ts index 97fd2c219..5bcc469bd 100644 --- a/apps/tests/file-system-tests.ts +++ b/apps/tests/file-system-tests.ts @@ -638,4 +638,14 @@ export function test_UnlockAfterWrite(done) { return file.remove(); }).then(() => done()) .catch(done); +} + +export function test_CreateParentOnNewFile(done) { + var documentsFolderName = fs.knownFolders.documents().path; + var tempFileName = fs.path.join(documentsFolderName, "folder1", "folder2", "Test_File_Create_Parent.txt"); + var file = fs.File.fromPath(tempFileName); + file.writeText("Hello World!").then(() => { + return fs.knownFolders.documents().getFolder("folder1").remove(); + }).then(() => done()) + .catch(done); } \ No newline at end of file diff --git a/file-system/file-system-access.android.ts b/file-system/file-system-access.android.ts index 0b74fea65..7e3c6eded 100644 --- a/file-system/file-system-access.android.ts +++ b/file-system/file-system-access.android.ts @@ -327,6 +327,7 @@ export class FileSystemAccess { if (isFolder) { created = javaFile.mkdirs(); } else { + javaFile.getParentFile().mkdirs(); created = javaFile.createNewFile(); } diff --git a/file-system/file-system-access.ios.ts b/file-system/file-system-access.ios.ts index b12bf0aff..7e796fcd6 100644 --- a/file-system/file-system-access.ios.ts +++ b/file-system/file-system-access.ios.ts @@ -52,11 +52,12 @@ export class FileSystemAccess { var exists = fileManager.fileExistsAtPath(path); if (!exists) { - if (!fileManager.createFileAtPathContentsAttributes(path, null, null)) { + var parentPath = this.getParent(path, onError).path; + if (!fileManager.createDirectoryAtPathWithIntermediateDirectoriesAttributesError(parentPath, true, null) || + !fileManager.createFileAtPathContentsAttributes(path, null, null)) { if (onError) { - onError(new Error("Failed to create folder at path '" + path + "'")); + onError(new Error("Failed to create file at path '" + path + "'")); } - return undefined; } } @@ -406,4 +407,4 @@ export class FileSystemAccess { var nsString = NSString.stringWithString(NSString.pathWithComponents(nsArray)); return nsString.stringByStandardizingPath; } -} \ No newline at end of file +}