2012-12-24 51 views
1

我使用下面的代碼來創建應用程序安裝文件夾中的文件夾,但我alwasy接收訪問被拒絕的異常。在windwos8創建文件夾訪問被拒絕

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

告訴我們哪一行引發異常,創建文件夾或檢查文件夾是否存在可能很有用? – Lukazoid

+0

謝謝@Lukazoid!在CheckIfFolderExist方法中引發異常,第五行GetFolderAsync。 – James

+0

您無權訪問該文件夾?奇怪的是你有一個FileNotFoundException,你可以添加一個額外的[DirectoryNotFoundException catch](http://msdn.microsoft.com/en-us/library/system.io.directorynotfoundexception.aspx)來確認。我看到你的下一個評論,請仍然用'try-catch'中的附加捕獲來確認。歡呼 –

回答

7

您無法在應用程序數據文件夾中創建文件夾。您必須使用LocalFolder,RomaingFolder或TemporaryFolder(全部在ApplicationData類中找到)

原因是爲了支持軟件升級等。爲什麼要保存在appdata文件夾中 - 也許我可以建議最好的以上使用的文件夾。

+0

之前定義的字符串類型Hi @Ross,感謝您的回覆,我想將一些用戶數據存儲在xml文件中,每個用戶都需要一個xml文件,所以我想創建一個文件夾,我可以將文件夾存儲在Documents Libary中? – James

+0

不,在這種情況下LocalFolder是正確的地方。 (如果它只是一個小文件RomaingFolder會更好,因爲它會與用戶同步)。我描述的所有文件夾都是用戶特定的。 –

相關問題