question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Maui media picker on Windows Platform error

See original GitHub issue

I have created a very basic MauiApp because I wanted to try the MediaPicker on the Windows Platform.

Thus I copied the code from the official documentation and tried to run my application

However if I add <uap:Capability Name="webcam"/> to the Package.appxmanifest file as suggested in the documentaion, and run the application it gives me the following error:

Error		DEP0700: Registration of the app failed. [0x80080204] error 0xC00CE169: App 
manifest validation error: The app manifest must be valid as per schema: Line 39, Column 
21, Reason: 'webcam' violates enumeration constraint of 'documentsLibrary 
picturesLibrary videosLibrary musicLibrary enterpriseAuthentication 
sharedUserCertificates userAccountInformation removableStorage appointments contacts 
phoneCall blockedChatMessages objects3D voipCall chat'.
The attribute 'Name' with value 'webcam' failed to parse.	MauiApp3			

So in order to solve this problem I tried to change the capability from <uap:Capability Name="webcam"/> to <DeviceCapability Name="webcam"/>.

In this way I can run the application without errors, but photo is always null:

public async void TakePhoto(object sender, EventArgs e)
{
    if (MediaPicker.Default.IsCaptureSupported)
    {
        FileResult photo = await MediaPicker.Default.CapturePhotoAsync();
        
        if (photo != null)
        {
            // save the file into local storage
            string localFilePath = Path.Combine(FileSystem.CacheDirectory, photo.FileName);

            using Stream sourceStream = await photo.OpenReadAsync();
            using FileStream localFileStream = File.OpenWrite(localFilePath);

            await sourceStream.CopyToAsync(localFileStream);
        }
        else
        {
            // *** IT ALWAYS ENTERS IN THE ELSE CLAUSE ***
            // *** BECAUSE photo IS ALWAYS NULL ***
            CounterBtn.Text = $"Capture is supported but {photo} is null";
        }
    }
}

Note: The function above is called when I click to this button that I’ve defined in MainPage.xaml file:

        <Button 
            x:Name="ImageBtn"
            Text="Take Photo"
            SemanticProperties.Hint="Take Image"
            Clicked="TakePhoto"
            HorizontalOptions="Center" />

Stackoverflow question: https://stackoverflow.com/questions/72450077/maui-media-picker-on-windows-platform-error

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:9 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
GiampaoloGabbacommented, Jun 10, 2022

Unfortunately this is a old and known bug for WinUI3. https://github.com/microsoft/WindowsAppSDK/issues/1034

As a workaround you can create a custom mediapicker that inherit everything from the MAUI one for Android, iOS and Catalyst.

Them implement a custom mediapicker for Windows, intheriting all the Capture... methods and reimplementing the CapturePhotoAsync using a custom class for camera capture:

public async Task<FileResult> CaptureAsync(MediaPickerOptions options, bool photo)
{
	var captureUi = new CameraCaptureUI(options);

	var file = await captureUi.CaptureFileAsync(photo ? CameraCaptureUIMode.Photo : CameraCaptureUIMode.Video);

	if (file != null)
        return new FileResult(file.Path,file.ContentType);

	return null;
}

This is the class:

using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.System;
using Microsoft.Maui.Platform;
using WinRT.Interop;

public class CameraCaptureUI
{
    private LauncherOptions _launcherOptions;

    public CameraCaptureUI(MediaPickerOptions options)
    {
        var hndl = WindowStateManager.Default.GetActiveWindow().GetWindowHandle();

        _launcherOptions = new LauncherOptions();
        InitializeWithWindow.Initialize(_launcherOptions, hndl);

        _launcherOptions.TreatAsUntrusted                   = false;
        _launcherOptions.DisplayApplicationPicker           = false;
        _launcherOptions.TargetApplicationPackageFamilyName = "Microsoft.WindowsCamera_8wekyb3d8bbwe";
    }

    public async Task<StorageFile> CaptureFileAsync(CameraCaptureUIMode mode)
    {
        if (mode != CameraCaptureUIMode.Photo)
        {
            throw new NotImplementedException();
        }

        var currentAppData = ApplicationData.Current;
        var tempLocation = currentAppData.TemporaryFolder;
        var tempFileName = "CCapture.jpg";
        var tempFile = await tempLocation.CreateFileAsync(tempFileName, CreationCollisionOption.GenerateUniqueName);
        var token = Windows.ApplicationModel.DataTransfer.SharedStorageAccessManager.AddFile(tempFile);

        var set = new ValueSet
        {
            { "MediaType", "photo"},
            { "PhotoFileToken", token }
        };

        var uri    = new Uri("microsoft.windows.camera.picker:");
        var result = await Windows.System.Launcher.LaunchUriForResultsAsync(uri, _launcherOptions, set);
        if (result.Status == LaunchUriStatus.Success)
        {
            return tempFile;
        }

        return null;
    }
}

The only downside is that with this class you cannot take videos on windows.

5reactions
richardrigutinscommented, Jun 12, 2022

Actually, with a slight modification in the custom CameraCaptureUI class, @GiampaoloGabba’s workaround can be used to capture both photos and videos on Windows:

public async Task<StorageFile> CaptureFileAsync(CameraCaptureUIMode mode)
{
	var extension = mode == CameraCaptureUIMode.Photo ? ".jpg" : ".mp4";

	var currentAppData = ApplicationData.Current;
	var tempLocation = currentAppData.LocalCacheFolder;
	var tempFileName = $"CCapture{extension}";
	var tempFile = await tempLocation.CreateFileAsync(tempFileName, CreationCollisionOption.GenerateUniqueName);
	var token = Windows.ApplicationModel.DataTransfer.SharedStorageAccessManager.AddFile(tempFile);

	var set = new ValueSet();
	if (mode == CameraCaptureUIMode.Photo)
	{
		set.Add("MediaType", "photo");
		set.Add("PhotoFileToken", token);
	}
	else
	{
		set.Add("MediaType", "video");
		set.Add("VideoFileToken", token);
	}

	var uri = new Uri("microsoft.windows.camera.picker:");
	var result = await Windows.System.Launcher.LaunchUriForResultsAsync(uri, _launcherOptions, set);
	if (result.Status == LaunchUriStatus.Success && result.Result != null)
	{
		return tempFile;
	}

	return null;
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Maui media picker on Windows Platform error
1 Answer 1 ... As a workaround you can create a custom mediapicker that inherit everything from the MAUI one for Android, iOS...
Read more >
Media picker for photos and videos - .NET MAUI
Learn how to use the IMediaPicker interface in the Microsoft.Maui.Media namespace, to prompt the user to select or take a photo or video....
Read more >
Troubleshoot known issues - .NET MAUI
The solution to this issue on Windows is to uninstall the .NET MAUI workloads through the CLI, uninstall any .NET SDKs in Control...
Read more >
File picker - .NET MAUI
Learn how to use the .NET MAUI IFilePicker interface in the Microsoft.Maui.Storage namespace, which lets a user choose one or more files ...
Read more >
Permissions - .NET MAUI
NET Multi-platform App UI (.NET MAUI) Permissions class. This class allows you to check and request permissions at run-time.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found