尝试将照片第二次保存到同一文件时出现UnauthorizedAccessException

时间:2013-06-28 21:09:01

标签: c# windows-8

所以,下面的代码允许我拍照。然后我显示图片。我的XAML绑定到Photo对象的Vehicle属性。它工作正常,直到我进去并尝试再拍照。然后我得到一个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);
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

我假设StoragePhoto封装了某种文件I / O。您必须正确处置这些对象,以释放将保持“挂钩”到文件中的基础非托管OS资源。如果您不处置它们,应用程序将保持对文件的访问权限,这可能是您第二次访问该文件会给您一个例外(第一次访问仍然存在)的原因。向我展示StoragePhoto代码,我可以更具体。

另外请注意,如果此应用程序是多线程的,您应该创建粒状信号量/锁定,将文件写入磁盘(可能通过实际物理路径字符串并锁定该引用),以确保您不要尝试

将同一文件同时写入同一物理路径的磁盘上