PhoneGap (Android) Delete Directory

后端 未结 2 2032
自闭症患者
自闭症患者 2020-12-19 17:55

I\'m trying to delete a directory and it\'s contents with PhoneGap on Android using:

deleteDirectory = function deleteDirectory(uri) {
    uri =         


        
相关标签:
2条回答
  • 2020-12-19 18:33

    I have done it with this approach:

    
    
        function ClearDirectory() {
            window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, fail);
            function fail(evt) {
                alert("FILE SYSTEM FAILURE" + evt.target.error.code);
            }
            function onFileSystemSuccess(fileSystem) {
                fileSystem.root.getDirectory(
                     "yours/dir/ect/ory",
                    {create : true, exclusive : false},
                    function(entry) {
                    entry.removeRecursively(function() {
                        console.log("Remove Recursively Succeeded");
                    }, fail);
                }, fail);
            }
        }
    
    
    
    0 讨论(0)
  • 2020-12-19 18:55

    From this answer:

    I'd suggest using resolveLocalFileSystemURL if you want to access locations under cordova.file.* (eg cordova.file.dataDirectory), which is most of the time (if not always), and use requestFileSystem if you need to have access to the root of the filesystem.

    This also saves some lines of code and is more readable:

    deleteFolder(fileName: string) {
        const uri = `${cordova.file.dataDirectory}${fileName}`;
        window.resolveLocalFileSystemURL(uri, (dirEntry: DirectoryEntry) => {
            dirEntry.removeRecursively(
                () => console.log('successfully deleted the folder and its content'),
                e => console.error('there was an error deleting the directory', e.toString())
            )
        });
    }
    

    And here an awaitable version:

    deleteFolder(fileName: string): Promise<void> {
        const promise = new Promise<void>((resolve, reject) => {
            const uri = `${cordova.file.dataDirectory}${fileName}`;
            window.resolveLocalFileSystemURL(uri, (dirEntry: DirectoryEntry) => {
                dirEntry.removeRecursively(() => resolve(), e => reject(e));
            }, e => reject(e));
        });
        return promise;
    }
    
    0 讨论(0)
提交回复
热议问题