Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a folder in a Windows Store App

How do you copy a folder and its contents in Windows Store Apps?

I'm writing tests for a Windows Store App. The app does things with files, so a set of known files is needed. Ideally, any developer could run these tests without requiring that they do some manual setup.

I assume that means test files would be checked into source control and then copied to the LocalState folder where tests could consume them (copy during ClassInitialize test phase).

StorageFile has copy functions. It would be possible to to use these to recursively rebuild the folder to copy. However it's hard to believe that this would be the correct approach... surely I'm missing something.

like image 809
Tristan Avatar asked Nov 25 '25 20:11

Tristan


1 Answers

This is rough and not thoroughly tested. It copies folders recursively. For name collisions, it overwrites existing files and folders.

    public static async Task CopyAsync(
        StorageFolder source, 
        StorageFolder destination)
    {
        // If the destination exists, delete it.
        var targetFolder = await destination.TryGetItemAsync(source.DisplayName);

        if (targetFolder is StorageFolder)
            await targetFolder.DeleteAsync();

        targetFolder = await destination.CreateFolderAsync(source.DisplayName);

        // Get all files (shallow) from source
        var queryOptions = new QueryOptions
        {
            IndexerOption = IndexerOption.DoNotUseIndexer,  // Avoid problems cause by out of sync indexer
            FolderDepth = FolderDepth.Shallow,
        };
        var queryFiles = source.CreateFileQueryWithOptions(queryOptions);
        var files = await queryFiles.GetFilesAsync();

        // Copy files into target folder
        foreach (var storageFile in files)
        {
            await storageFile.CopyAsync((StorageFolder)targetFolder, storageFile.Name, NameCollisionOption.ReplaceExisting);
        }

        // Get all folders (shallow) from source
        var queryFolders = source.CreateFolderQueryWithOptions(queryOptions);
        var folders = await queryFolders.GetFoldersAsync();

        // For each folder call CopyAsync with new destination as destination
        foreach (var storageFolder in folders)
        {
            await CopyAsync(storageFolder, (StorageFolder)targetFolder);
        }
    }

Please, someone have a better answer. Copying a folder should be a one line call to a tested .net API. We shouldn't all have to write our own functions or copy-paste untested code from the internet.

like image 142
Tristan Avatar answered Nov 28 '25 14:11

Tristan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!