如何在Windows应用商店应用中复制文件夹及其内容?
我正在为Windows应用商店应用编写测试。该应用程序使用文件,因此需要一组已知文件。理想情况下,任何开发人员都可以运行这些测试,而无需他们进行一些手动设置。
我认为这意味着测试文件将被检入源代码控制,然后被复制到LocalState
文件夹中,测试可以使用它们(在ClassInitialize
测试阶段复制)。
StorageFile具有复制功能。可以使用这些来递归重建要复制的文件夹。然而,很难相信这将是正确的方法......当然我错过了一些东西。
答案 0 :(得分:5)
这很粗糙,未经过彻底测试。它以递归方式复制文件夹。对于名称冲突,它会覆盖现有文件和文件夹。
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);
}
}
请有人有更好的答案。复制文件夹应该是对测试的.net API的单行调用。我们不应该都必须编写自己的函数或从互联网上复制粘贴未经测试的代码。
答案 1 :(得分:0)
以下是我复制文件夹的版本,如果在IStorageFolder
上有3种扩展方法:
代码:
public static class StorageFolderExtensions
{
/// <summary>
/// Recursive copy of files and folders from source to destination.
/// </summary>
public static async Task CopyContentsRecursive(this IStorageFolder source, IStorageFolder dest)
{
await CopyContentsShallow(source, dest);
var subfolders = await source.GetFoldersAsync();
foreach (var storageFolder in subfolders)
{
await storageFolder.CopyContentsRecursive(await dest.GetFolderAsync(storageFolder.Name));
}
}
/// <summary>
/// Shallow copy of files and folders from source to destination.
/// </summary>
public static async Task CopyContentsShallow(this IStorageFolder source, IStorageFolder destination)
{
await source.CopyFiles(destination);
var items = await source.GetFoldersAsync();
foreach (var storageFolder in items)
{
await destination.CreateFolderAsync(storageFolder.Name, CreationCollisionOption.ReplaceExisting);
}
}
/// <summary>
/// Copy files from source into destination folder.
/// </summary>
private static async Task CopyFiles(this IStorageFolder source, IStorageFolder destination)
{
var items = await source.GetFilesAsync();
foreach (var storageFile in items)
{
await storageFile.CopyAsync(destination, storageFile.Name, NameCollisionOption.ReplaceExisting);
}
}