在Windows 8中创建文件夹访问被拒绝

时间:2012-12-24 09:41:03

标签: c# windows-8 io windows-runtime local-storage

我使用下面的代码在app安装的文件夹中创建文件夹,但我还是接收了访问被拒绝的异常。

StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
        if (!await CheckIfFolderExist(appDataFolderName))
        {                
            StorageFolder appDataFolder = await appFolder.CreateFolderAsync(appDataFolderName);
            StorageFolder userFolder = await appDataFolder.CreateFolderAsync(userFolderName);
            StorageFolder contactFolder = await appDataFolder.CreateFolderAsync(contactFolderName);
        }
        else
        {
            StorageFolder appDataFolder = await appFolder.GetFolderAsync(appDataFolderName);
            if (!await CheckIfSubFolderExis(appDataFolderName, userFolderName))
            {
                await appDataFolder.CreateFolderAsync(userFolderName);
            }
            if (!await CheckIfSubFolderExis(appDataFolderName, contactFolderName))
            {
                await appDataFolder.CreateFolderAsync(contactFolderName);
            }
        }

 // Check if the app folder exists
    private async Task<bool> CheckIfFolderExist(string folderName )
    {
        bool folderExist = false;
        try
        {
            StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder appDataFolder = await appFolder.GetFolderAsync(folderName);                
            folderExist = true;
            return folderExist;
        }
        catch (FileNotFoundException ex)
        {
            return folderExist;
        }
    }

    // Check if the app subfolder exists
    private async Task<bool> CheckIfSubFolderExis(string folderName,string subFolderName)
    {
        bool subFolderExist = false;
        try
        {
            StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            StorageFolder subFolder = await appFolder.GetFolderAsync(subFolderName);
            subFolderExist = true;
            return subFolderExist;
        }
        catch (FileNotFoundException ex)
        {
            return subFolderExist;
        }
    }

有人有想法吗?

1 个答案:

答案 0 :(得分:7)

您无法在应用数据文件夹中创建文件夹。您必须使用LocalFolder,RomaingFolder或TemporaryFolder(均在ApplicationData类中找到)

这样做的原因是支持软件升级等。为什么要保存在appdata文件夹中 - 也许我可以建议使用上面最好的文件夹。