Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 42 ยท Platform Features

Camera, Files and Sharing

Take photos with MediaPicker, pick files with FilePicker, share text and files, use the clipboard and launch other apps in .NET MAUI, with safe stream handling.

Apps become useful when they connect to the rest of the phone: take a picture, attach a PDF, share a result with a friend, open a link in the browser. .NET MAUI Essentials covers all of these with a handful of static classes. The patterns are similar: call an async method, get back a result object that may be null if the user cancels, and read a stream.

These APIs open native pickers and cannot run in the browser. The MAUI snippets are read-only. The runnable stand-ins model the parts you write yourself: validating file types, resizing math, and copying streams safely.

Taking and picking photos: MediaPicker

C#
public async Task<string?> TakePhotoAsync()
{
    if (!MediaPicker.Default.IsCaptureSupported)
    {
        return null;
    }

    FileResult? photo = await MediaPicker.Default.CapturePhotoAsync();
    if (photo is null)
    {
        return null;            // user cancelled
    }

    string target = Path.Combine(FileSystem.CacheDirectory, photo.FileName);
    using Stream source = await photo.OpenReadAsync();
    using FileStream destination = File.Create(target);
    await source.CopyToAsync(destination);
    return target;
}

Notes:

  • CapturePhotoAsync needs the camera permission (see Permissions). On Android the manifest needs a <queries> entry for the image-capture intent.
  • PickPhotoAsync() opens the gallery instead, CaptureVideoAsync and PickVideoAsync do the same for video, and PickPhotosAsync lets the user select several photos.
  • A FileResult is not always a real file path. Treat it as a stream source: call OpenReadAsync() and copy it into your own storage.
  • Show the result with ImageSource.FromFile(path) or ImageSource.FromStream(...).

In .NET 10 MediaPicker also accepts MediaPickerOptions, for example to set a title or, on some platforms, to compress and resize the image while picking. Check the options for your target platforms in the release notes of the version you use.

Picking any file: FilePicker

C#
var options = new PickOptions
{
    PickerTitle = "Choose a CSV file",
    FileTypes = new FilePickerFileType(new Dictionary<DevicePlatform, IEnumerable<string>>
    {
        { DevicePlatform.Android, new[] { "text/csv" } },
        { DevicePlatform.iOS, new[] { "public.comma-separated-values-text" } },
        { DevicePlatform.WinUI, new[] { ".csv" } },
        { DevicePlatform.MacCatalyst, new[] { "public.comma-separated-values-text" } },
    })
};

FileResult? result = await FilePicker.Default.PickAsync(options);
if (result is not null)
{
    using Stream stream = await result.OpenReadAsync();
    using var reader = new StreamReader(stream);
    string text = await reader.ReadToEndAsync();
}

Every platform names file types differently: MIME types on Android, uniform type identifiers on Apple platforms and extensions on Windows. FilePicker.Default.PickMultipleAsync returns several files. Predefined values such as FilePickerFileType.Images and FilePickerFileType.Pdf save you the dictionary.

Never trust the file name or type the user picked. Check the extension and size before you process it.

Sharing

The system share sheet is one call:

C#
await Share.Default.RequestAsync(new ShareTextRequest
{
    Title = "My result",
    Text = "I scored 42 points!",
    Uri = "https://example.com/scores/42"
});

await Share.Default.RequestAsync(new ShareFileRequest
{
    Title = "Export",
    File = new ShareFile(pathToFile)
});

The user picks the target app, and you never see which one. This is a privacy feature.

Clipboard, browser and launcher

C#
await Clipboard.Default.SetTextAsync("INV-2026-0042");
string? pasted = await Clipboard.Default.GetTextAsync();

await Browser.Default.OpenAsync("https://learn.example.com", BrowserLaunchMode.SystemPreferred);

if (await Launcher.Default.CanOpenAsync("tel:+1555000111"))
{
    await Launcher.Default.OpenAsync("tel:+1555000111");
}

await Email.Default.ComposeAsync(new EmailMessage
{
    Subject = "Feedback",
    To = new List<string> { "[email protected]" }
});

BrowserLaunchMode.SystemPreferred opens an in-app browser tab, while External leaves your app. Also see PhoneDialer, Sms and Map.Default.OpenAsync(location).

flowchart LR
    U["User taps button"] --> P["Native picker or share sheet"]
    P -- cancel --> N["null result"]
    P -- choose --> F["FileResult"]
    F --> S["OpenReadAsync() stream"]
    S --> C["Validate, copy to app storage"]

A picker always returns a result you must validate; null means the user backed out.

Try it: validating a picked file

Before you read a user-supplied file, check its extension and size. This stand-in implements a small, testable validator that does not depend on any UI.

C# Stand-in: file validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last case shows why you should never combine a user-supplied name with a folder path directly. Use Path.GetFileName(name) or generate your own file names.

Try it: copying a stream and sizing an image

A FileResult hands you a stream. Copying it to your own storage in a buffered loop works for any size. Here a MemoryStream plays the role of the picked file, and a helper computes the dimensions for a thumbnail that keeps the aspect ratio.

C# Stand-in: stream copy and thumbnail size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Photos from a modern phone are many megabytes. Resize before you upload or store them, and always dispose streams with using.

Common mistakes

  • Assuming the picker returns a file path you can reuse tomorrow. Copy the data into FileSystem.AppDataDirectory if you need it later.
  • Forgetting the iOS Info.plist strings for photo library access.
  • Not handling null (cancel) or PermissionException.
  • Loading a whole 12 MP photo into an Image without downsampling.
  • Doing the file work on the UI thread. Use await and Task.Run for heavy processing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does CapturePhotoAsync return when the user cancels?

    A cancelled picker returns null, so check for it before using the result.
  2. 2. Why does FilePickerFileType take a dictionary keyed by DevicePlatform?

    Android uses MIME types, Apple platforms use UTIs and Windows uses extensions.
  3. 3. What is the safest way to keep a picked photo for later?

    The picked location may be temporary or inaccessible later, so copy the data to your own folder.
  4. 4. What does the Share API tell you about the chosen target app?

    The share sheet intentionally hides which app the user picked.

Summary

  • MediaPicker, FilePicker, Share, Clipboard, Browser, Launcher and Email cover most "talk to the phone" needs.
  • Results can be null; treat a FileResult as a stream source and copy it.
  • Validate file names, extensions and sizes yourself, and resize large images.
  • Always declare the permissions and platform entries the picker needs.

Next: Preferences and Secure Storage