0

在我的應用程序中,我將位圖轉換爲PNG並將其存儲在文件夾內的文件中。當我試圖再次打開文件寫第二次時,我得到一個UnauthorisedAccessException"Access is denied"。 單擊保存按鈕時,將調用以下函數。UnauthorizedAcessException嘗試從WP8中的文件夾打開文件

private async void SaveClicked(object sender, RoutedEventArgs e) 
     { 
      WriteableBitmap wb = new WriteableBitmap(InkCanvas2, null); 
      Image image = new Image(); 
      image.Height = 150; 
      image.Width = 450; 
      image.Source = wb; 
      await SaveToStorage(wb, image); 
      TransparentLayer.Visibility = System.Windows.Visibility.Collapsed; 

     } 

的SaveToStorage具有下面的代碼

private async Task SaveToStorage(WriteableBitmap i, Image im) 
     { 
      try 
      {  
        var dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists);      
        using (var testpng = await dataFolder.OpenStreamForWriteAsync("testpng.png", CreationCollisionOption.ReplaceExisting)) 
// HITS EXCEPTION AND GOES TO CATCH BLOCK 
        {  
         i.WritePNG(testpng);  
         testpng.Flush(); 
         testpng.Close(); 
        }      
      } 
      catch(Exception e) 
      { 
      string txt = e.Message; 
      } 
     } 

它節省了第一次,沒有錯誤,第二時間,則拋出異常。任何想法爲什麼發生這種情況

回答

0

我想通了!很明顯,因爲在嘗試打開它之前我沒有包含文件存在檢查。

我已經重新寫成這樣

 IStorageFolder dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists); 
      StorageFile Ink_File = null; 
      //Using try catch to check if a file exists or not as there is no inbuilt function yet 
      try 
      { 
       Ink_File = await dataFolder.GetFileAsync("testpng.png"); 
      } 
      catch (FileNotFoundException) 
      { 
       return false; 
      } 

      try 
      { 
       if (Ink_File != null) 
       { 

        using (var testpng = await Ink_File.OpenStreamForWriteAsync()) 
        { 

         i.WritePNG(testpng); 

         testpng.Flush(); 
         testpng.Close(); 
         return true; 
        } 
       } 

      } 
      catch(Exception e) 
      { 
       string txt = e.Message; 
       return false; 
      } 
      return false; 
代碼
相關問題