Search code examples
c#exceptionuwpwindows-10-mobile

windows 10 mobile camera


I'm trying to use the camera in a Windows 10 Mobile App but an error is occurring when I take the picture and try to show it on the screen.

Here's the code:

CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Jpeg;
captureUI.PhotoSettings.CroppedSizeInPixels = new Size(200, 200);

StorageFile photo = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (photo == null)
{
    // User cancelled photo capture
    return;
}

StorageFolder destinationFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("ProfilePhotoFolder", CreationCollisionOption.OpenIfExists);

await photo.CopyAsync(destinationFolder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
await photo.DeleteAsync();

IRandomAccessStream stream = await photo.OpenAsync(FileAccessMode.Read);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

SoftwareBitmap softwareBitmapBGR8 = SoftwareBitmap.Convert(softwareBitmap,
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied);

SoftwareBitmapSource bitmapSource = new SoftwareBitmapSource();
await bitmapSource.SetBitmapAsync(softwareBitmapBGR8);

imageControl.Source = bitmapSource;

The exception message:

An exception of type 'System.IO.FileNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code

Additional information: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

If there is a handler for this exception, the program may be safely continued."

Someone can help me with this?


Solution

  • This is because you deleted the photo but then trying to read the photo which has just deleted, so the exception "FileNotFound" will throw. Please remove the following code line it will work.

     await photo.DeleteAsync();
    

    But I think what you really want to do is to delete the photo which is got from the CameraCaptureUI, and then read the photo from the local folder which has already copied. In that case, code should be as followings:

    await photo.CopyAsync(destinationFolder, "ProfilePhoto.jpg", NameCollisionOption.ReplaceExisting);
    await photo.DeleteAsync();
    StorageFile newphoto = await destinationFolder.GetFileAsync("ProfilePhoto.jpg");
    IRandomAccessStream stream = await newphoto.OpenAsync(FileAccessMode.Read);