Search code examples
c#windows-8copywinrt-async

Copy Folder on WinRT


For now, I just know how to copy file using:

IStorageFolder dir = Windows.Storage.ApplicationData.Current.LocalFolder;

IStorageFile file = await StorageFile.GetFileFromApplicationUriAsync(
    new Uri("ms-appx:///file.txt"));

await file.CopyAsync(dir, "file.txt");

When I try to copy folder and all the content inside, I cannot find the API like CopyAsync above.

Is it possible to copy folder and all the content in WinRT?


Solution

  • Code above didn't satisfy me (too specific), i made my own generic one so figured i could share it :

    public static async Task CopyFolderAsync(StorageFolder source, StorageFolder destinationContainer, string desiredName = null)
        {
            StorageFolder destinationFolder = null;
                destinationFolder = await destinationContainer.CreateFolderAsync(
                    desiredName ?? source.Name, CreationCollisionOption.ReplaceExisting);
    
            foreach (var file in await source.GetFilesAsync())
            {
                await file.CopyAsync(destinationFolder, file.Name, NameCollisionOption.ReplaceExisting);
            }
            foreach (var folder in await source.GetFoldersAsync())
            {
                await CopyFolderAsync(folder, destinationFolder);
            }
        }