다음을 통해 공유


Copying folder (and subfolders) from install location to local storage with WinJS

The other day, I wanted to copy content of a folder (including all of its subfolder) that was packaged with my AppX to my local storage.

Before calling CopyFolder, I’d recommend checking to make sure the folder you want to copy is not already there. You can do so by calling getAsyncFolder. Also, to ensure your files are actually packaged into the AppX, make sure you set the build action for the file to “Copy Always”. (E.g. In the Properties pane, set Copy to Output Directory to “Copy always”)

 

Here is the code:

var applicationData = Windows.Storage.ApplicationData.current;
var localFolder = applicationData.localFolder;

 function CopyFolder(source) {
    var installFolder = Windows.ApplicationModel.Package.current.installedLocation;
    installFolder.getFolderAsync(source).then(function (folder) {
        CopySubFolders(folder, localFolder);
    },
    function (folder) {
        console.log("folder not found: " + folder.name);
        return;
    
     })
    function CopySubFolders(folder, destFolder) {
        if (folder == null)
            return;

        // Copy the files
        folder.getFilesAsync().then(function (files) {
            if (files != null) {
                files.forEach(function (result) {
                    console.log("copy file: " + result.displayName);
                    result.copyAsync(destFolder);
                });
            }
        });

        // Recursively copy each subfolder
        folder.getFoldersAsync().then(function (folderlist) {
            folderlist.forEach(function (result) {
                var replace = Windows.Storage.CreationCollisionOption.replaceExisting;
                console.log("create folder: " + result.name);
                destFolder.createFolderAsync(result.name, replace).then(function (newdest) {
                    CopySubFolders(result, newdest);
                });
            });
        });
    }
}


    

Let me know whether that works for you. Now that I am back to blogging, please let me know whether this is useful and what else you’d like me to blog about!

 

Here are some resources: