簡體   English   中英

嘗試將照片再次保存到同一文件時,出現UnauthorizedAccessException

[英]UnauthorizedAccessException when trying to save a photo to the same file a second time

因此,下面的代碼允許我拍照。 然后顯示圖片。 我的XAML綁定到Vehicle對象的Photo屬性。 效果很好,直到我進入並嘗試再次拍照。 然后,我得到一個UnauthorizedAccessException 我在“ LocalStorage”中創建文件,所以我認為我不需要特殊權限才能在其中寫入文件。 我不確定是什么引起了錯誤。

public async Task TakePicture()
    {
        CameraCaptureUI camera = new CameraCaptureUI();
        camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
        StorageFile photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

        if (photo != null)
        {
            var targetFolder = ApplicationData.Current.LocalFolder;
            var targetFile = await targetFolder.CreateFileAsync(String.Format
                ("VehiclePhoto{0}.jpg", this.Vehicle.PrimaryKey), CreationCollisionOption.ReplaceExisting);
            if (targetFile != null)
            {
                await photo.MoveAndReplaceAsync(targetFile);
                this.Vehicle.Photo = String.Format("ms-appdata:///local/VehiclePhoto{0}.jpg", this.Vehicle.PrimaryKey);
            }
        }
    }

我假設StoragePhoto封裝了某種文件I / O。 您必須正確處理這些對象,以便釋放將“鈎子”保留在文件中的底層非托管OS資源。 如果您不處理它們,則應用程序將保持對文件的訪問保持打開狀態,這可能就是為什么您對文件的第二次訪問為您提供異常(第一次訪問仍然存在)的原因。 告訴我StoragePhoto代碼,我可以更具體一些。

另一個需要注意的是,如果該應用程序是多線程的,則應該圍繞將文件寫入磁盤(可能是通過物理路徑字符串並鎖定該引用)創建粒度信號燈/鎖,以確保您不嘗試編寫相同的信號燈/鎖。在同一時間在同一物理路徑上將文件復制到磁盤-那就不好了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM