• This repository has been archived on 14/Jan/2021
  • Stars
    star
    156
  • Rank 239,589 (Top 5 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 7 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

FilePicker Plugin for Xamarin and Windows

FilePicker Plugin for Xamarin.Forms

Simple cross-platform plug-in that allows you to pick files and work with them.

The original project can be found here, but seems abandoned, this one was forked and further developed.

The future: Xamarin.Essentials

Since version 1.6.0 the Xamarin.Essentials project also supports file picking! See the Migration Guide on how to migrate from this plugin to the official Xamarin.Essentials API!

Build status

Stable Build status NuGet version

NuGet: https://www.nuget.org/packages/Xamarin.Plugin.FilePicker/

Development feed (possibly instable)

Add this as a source to your IDE to find the latest packages: https://www.myget.org/F/filepicker-plugin/api/v3/index.json

Setup

  • Install into your Xamarin.Android, Xamarin.iOS, Xamarin.Forms, Xamarin.Mac, Xamarin.WPF project and Client projects.

Platform Support

Platform Supported Version Remarks
Xamarin.iOS Classic Yes iOS 8+
Xamarin.iOS Unified Yes iOS 8+
Xamarin.Android Yes API 10+
Windows Phone Silverlight No
Windows Phone RT Yes 8.1+ Up to package version 1.4.x
Windows Store RT Yes 8.1+ Up to package version 1.4.x
Windows 10 UWP Yes 10+
Xamarin.Mac Yes * 10.12+
WPF Yes N/A Using .NET Framework 4.5

* The Xamarin.Mac implementation has only been tested on MacOS 10.12.

API Usage

Call CrossFilePicker.Current from any platform or .NET Standard project to gain access to APIs.

Example

try
{
    FileData fileData = await CrossFilePicker.Current.PickFile();
    if (fileData == null)
        return; // user canceled file picking

    string fileName = fileData.FileName;
    string contents = System.Text.Encoding.UTF8.GetString(fileData.DataArray);

    System.Console.WriteLine("File name chosen: " + fileName);
    System.Console.WriteLine("File data: " + contents);
}
catch (Exception ex)
{
    System.Console.WriteLine("Exception choosing file: " + ex.ToString());
}

Methods

async Task<FileData> PickFile(string[] allowedTypes = null)

Starts file picking and returns file data for picked file. File types can be specified in order to limit files that can be selected. Note that this method may throw exceptions that occured during file picking.

Note that on Android it can happen that PickFile() can be called twice. In this case the first PickFile() call will return null as it is effectively cancelled.

Parameter allowedTypes: Specifies one or multiple allowed types. When null, all file types can be selected while picking.

On Android you can specify one or more MIME types, e.g. "image/png"; also wild card characters can be used, e.g. "image/*".

On iOS you can specify UTType constants, e.g. UTType.Image.

On UWP, specify a list of extensions, like this: ".jpg", ".png".

On WPF, specify strings like this: "Data type (*.ext)|*.ext", which corresponds how the Windows file open dialog specifies file types.

Data structures

The returned FileData object contains multiple properties that can be accessed:

public class FileData
{
    /// When accessed, reads all data from the picked file and returns it.
    public byte[] DataArray { get; }

    /// Filename of the picked file; doesn't contain any path.
    public string FileName { get; }

    /// Full file path of the picked file; note that on some platforms the
    /// file path may not be a real, accessible path but may contain an
    /// platform specific URI; may also be null.
    public string FilePath { get; }

    /// Returns a stream to the picked file; this is the most reliable way
    /// to access the data of the picked file.
    public Stream GetStream();
}

Note that DataArray is filled on first access, so be sure to rewind the stream when you access it via GetStream() afterwards.

IMPORTANT

Android: The FilePath property may contain a content URI that starts with content://. The plugin tries hard to find out an actual filename, but when it can't, the file can only be accessed using GetStream() or DataArray. On Android ContentProvider classes are used to share data between apps. The resource that is accessed may not even be a file, streamed over the internet or loaded from a database.

The plugin also tries to get a persistable content URI that can be stored for later access. Be prepared that this may fail, though. Content could have been moved to a different location or could be deleted.

The READ_EXTERNAL_STORAGE permission is automatically added to your Android app project. Starting from Android 6.0 (Marshmallow) the user is asked for the permission when not granted yet. When the user denies the permission, PickFile() returns null.

The WRITE_EXTERNAL_STORAGE is required if you call SaveFile() and must be added to your Android app project by yourself.

iOS: You need to Configure iCloud Driver for your app.

Migration guide

Migrating the usage of this FilePicker plugin to Xamarin.Essentials.FilePicker isn't straight-forward. It's similar, though, since the Essentials code originated from this plugin. Here's a little guide on how to do it.

  1. If you don't have the Xamarin.Essentials NuGet package installed yet, install it into the Android, iOS and UWP projects. Also install it into your Forms project, if you're calling the FilePicker from there. Be sure to also properly initialize Essentials. You can remove the Xamarin.Plugin.FilePicker NuGet package now or afterwards.

  2. Rename the namespaces, types and method calls. Replace

    using Plugin.FilePicker;
    using Plugin.FilePicker.Abstractions;
    

    with

    using Xamarin.Essentials;
    

    Replace await CrossFilePicker.Current.PickFile() with await FilePicker.PickAsync(). Replace FileData with FileResult (or use the var keyword).

  3. Use Xamarin.Essentials.PickOptions if you specified file types for picking. Replace code like this:

    string[] fileTypes = null;
    if (Device.RuntimePlatform == Device.Android)
        fileTypes = new string[] { "image/png", "image/jpeg" };
    
    if (Device.RuntimePlatform == Device.iOS)
        fileTypes = new string[] { "public.image" };
    
    if (Device.RuntimePlatform == Device.UWP)
        fileTypes = new string[] { ".jpg", ".png" };
    

    with:

    var options = new PickOptions
    {
        FileTypes = new FilePickerFileType(
            new Dictionary<DevicePlatform, IEnumerable<string>>
            {
                { DevicePlatform.Android, new string[] { "image/png", "image/jpeg"} },
                { DevicePlatform.iOS, new string[] { "public.image" } },
                { DevicePlatform.UWP, new string[] { ".jpg", ".png" } },
            }),
        PickerTitle = "Select a file to import"
    };
    

    If you can't specify a list of MIME types or file extensions, use null as the value of the dictionary entry, or else file picking on that platform won't be available:

    { DevicePlatform.Android, null },
    

    Note also that the PickerTitle is a new property, but the title is only shown on Android.

  4. Replace usage of FileData with Xamarin.Essentials.FileResult. The new FileResult structure has some properties and methods named differently. The biggest change is that you should not (and in some cases on Android can't) rely on FileResult.FullPath to be a file system filename. Always use FileResult.OpenStreamAsync() to get a stream to the picked file. From there you can either read from the stream directly (e.g. using a StreamReader), or copy the file into your app folder. This can be done using Stream.CopyToAsync() and has the advantage that you do the copying in a background task, and you can specify a CancellationToken that can be used to cancel the operation. You could even show a progress dialog to the user that allows cancelling the transfer.

Troubleshooting

All platforms

InvalidOperationException "Only one operation can be active at a time"

This occurs when PickFile() is called multiple times and the task being awaited didn't return or throws an exception that wasn't caught. Be sure to catch any exceptions and handle them appropriately. See the example code above.

Android

Exception "This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation."

This occurs when you are using the old-style NuGet references (not the PackageReference mechanism) and you forgot to add the NuGet package to the Android package. When using PackageReference this is not necessary anymore because the bait-and-switch assemblies of FilePicker are correctly resolved.

iOS

Picked file path is invalid, file doesn't exist

On iOS the plugin uses UIDocumentPickerViewController and specifies the mode UIDocumentPickerMode.Import. After picking is done, iOS copies the picked file to the app's temporary "Inbox" folder where it can be accessed. iOS also cleans up the temporary inbox folder regularly. After picking the file you have to either copy the file to another folder, access the data by getting the property DataArray or opening a stream to the file by calling GetStream().

Contributors

Thanks!

License

MIT Licence

More Repositories

1

learn-dotnet-maui

A repository filled with resources available to you to start learning or deepen your knowledge about .NET MAUI
392
star
2

Plugin.Maui.Audio

Plugin.Maui.Audio provides the ability to play audio inside a .NET MAUI application
C#
201
star
3

MauiFolderPickerSample

Sample code to demonstrate how to implement a folder picker with .NET MAUI
C#
50
star
4

pdfjs

A sample for showing PDF files in a Xamarin.Forms application with pdf.js
JavaScript
32
star
5

Plugin.Maui.ScreenBrightness

Plugin.Maui.ScreenBrightness provides the ability to get or set the screen brightness inside a .NET MAUI application.
C#
30
star
6

XFFCMPushNotificationsSample

Sample code to demonstrate how to implement push notifications in Xamarin.Forms with Firebase Cloud Messaging (FCM)
C#
24
star
7

ZXingSample

Working sample app for a blog post on barcode scanning and generating with ZXing
C#
23
star
8

TravelMonkey

TravelMonkey sample app for the Xamarin + Cognitive Services Crazy Combo Challenge
C#
21
star
9

AirplaneModeProof

This repository contains the sample code for my talk "Creating airplane mode proof Xamarin applications"
C#
20
star
10

XFBackgroundLocationSample

Sample code to demonstrate how to track a devices' background location with Xamarin.Forms
C#
19
star
11

EmbeddedFontsSample

Sample code to show the power of embedded fonts in Xamarin.Forms
C#
18
star
12

Plugin.Maui.ScreenRecording

Plugin.Maui.ScreenRecording provides the ability to record the screen from within your app
C#
18
star
13

MauiZxingBarcodeScannerSample

Sample code to demonstrate how to scan barcodes with ZXing and .NET MAUI
C#
18
star
14

been-pwned

App that leverages the haveibeenpwned.com API by Troy Hunt. This app is available in the App Stores and is used in several of my talks as well as my book Xamarin.Forms Essentials.
C#
16
star
15

MauiShellAppTemplate

.NET MAUI Shell Template
C#
15
star
16

Plugin.Maui.UITestHelpers

A set of helpers to support UI testing your .NET MAUI app and migration from Xamarin.UITest to Appium
C#
15
star
17

XamarinNotifications

The sample app for my blogposts about push notifications with Xamarin.Forms on https://blog.verslu.is
C#
15
star
18

MauiSpeechToTextSample

Sample code to demonstrate how to implement speech-to-text with .NET MAUI
C#
15
star
19

WifiBarcodeSample

Sample code for my article in DotNetCurry magazine on scanning barcodes. In this sample you can generate and scan QR codes that contain a Wi-Fi connection string
C#
15
star
20

MauiSignalRSample

Sample code to demonstrate how to get started with SignalR and .NET MAUI
C#
12
star
21

MauiLocalPushNotificationsSample

Sample code to demonstrate how to work with local push notifications in .NET MAUI
C#
12
star
22

XFDotNetExtensionsDISample

Sample code to demonstrate the use of Microsoft.Extensions.DependencyInjection with Xamarin.Forms
C#
12
star
23

XFUploadFile

Sample code to show how to upload a file from Xamarin.Forms
C#
12
star
24

AkavacheSample

Sample code for my blog post about Akavache
C#
11
star
25

XFSQLiteGettingStartedSample

Sample code to demonstrate how to get started with SQLite in your Xamarin.Forms or .NET MAUI app
C#
11
star
26

MauixUnitTestSample

Sample code to demonstrate how to add a xUnit test project to your .NET MAUI app
C#
11
star
27

MauiLocalizationSample

Sample code to demonstrate how to localize a .NET MAUI application
C#
11
star
28

MauiPlatformCodeDISample

Code to demonstrate how to write platform-specific code with dependency injection in .NET MAUI
C#
11
star
29

MauiCameraMauiSample

Sample code to demonstrate how to work with the Camera.MAUI plugin in .NET MAUI
C#
11
star
30

MauiEncryptedSqliteSample

Sample code to demonstrate how to work with a encrypted SQLite database in .NET MAUI (and Xamarin.Forms)
C#
11
star
31

LottieSample

C#
10
star
32

CustomFontsSample

A sample for showing how to use custom fonts in Android and iOS using Xamarin.Forms
C#
10
star
33

AlternateRowColorSample

Answer to a Stackoverflow question about how to implement an alternate row color in a Xamarin.Forms ListView
C#
10
star
34

MauiMapsSample

Sample code to demonstrate how to work with .NET MAUI Maps
C#
10
star
35

CastRadio

C#
9
star
36

XFUploadFileChunkedSample

Sample code to demonstrate how to upload a file through chuncks enabling cancellation, progress reporting and resuming uploads with Xamarin.Forms and ASP.NET
C#
9
star
37

MauiGithubActionsSample

Sample repository to show you how to build your .NET MAUI app with GitHub actions for Android, iOS, macOS and Windows
C#
9
star
38

MauiCollectionViewGroupingSample

Sample code to demonstrate how to implement grouping with .NET MAUI CollectionView
C#
9
star
39

MauiDesktopFeaturesSample

Sample code to demonstrate desktop features in .NET MAUI
C#
8
star
40

BeenPwned.Api

.NET Wrapper library for the haveibeenpwned.com API
C#
8
star
41

XFAdMobSample

Sample code to demonstrate the implementation of AdMob Ads in Xamarin.Forms
C#
8
star
42

XFScanBarcodeSample

Sample code to demonstrate barcode scanning with ZXing in Xamarin.Forms
C#
8
star
43

DifferentAppIconsSample

Sample code for the blog post: Different app icons for different configurations in Xamarin
C#
8
star
44

LoadXamlSample

Example code for loading XAML into a page and showing it for Xamarin.Forms
C#
7
star
45

MauiGoogleMapsSample

Sample code to demonstrate how to use the Maui.GoogleMaps plugin with .NET MAUI
C#
7
star
46

MauiMediaElementSample

Sample code to demonstrate how to get started with MediaElement in your .NET MAUI application
C#
7
star
47

MauiMopupsSample

Sample code to demonstrate how to work with Mopups in .NET MAUI
C#
7
star
48

XFDarkModeSample

C#
7
star
49

XCTPopupsSample

Sample code to demonstrate showing popups with Xamarin Community Toolkit in Xamarin.Forms apps
C#
7
star
50

XFMapsLiveTrackingSample

Sample code to demonstrate how to implement live tracking in Xamarin.Forms Maps
C#
7
star
51

ExistingSQLiteDbSample

Sample code to demonstrate how to work with an existing SQLite Database in Xamarin.Forms and .NET MAUI
C#
7
star
52

MauiToolkitSnackbarToastSample

Sample code to demonstrate how to work with Snackbar and Toast from the .NET MAUI Community Toolkit in your .NET MAUI app
C#
7
star
53

HideGoXLRWindow

This little solution hides the GoXLR App window on startup since there is no way to do that from the software itself
PowerShell
7
star
54

MauiDrawingViewSample

Sample code to demonstrate how to get started with the .NET MAUI Community Toolkit DrawingView
C#
7
star
55

AppCenterAnalyticsSample

Sample code to demonstrate how to add App Center Analytics to your Xamarin.Forms app
C#
7
star
56

MauiAndroidClearText

Sample code to demonstrate how to enable Android Cleartext Traffic in .NET MAUI
C#
6
star
57

DncMvvm

C#
6
star
58

MauiWindowsUnpackagesSample

Sample code to demonstrate how to build and distribute a so-called unpackaged Windows app with .NET MAUI
C#
6
star
59

MauiUnitTestSample

C#
6
star
60

MauiZXingBarcodeGeneratorSample

Sample code to demonstrate how to generate barcodes with ZXing and .NET MAUI
C#
6
star
61

MauiBlazorBindingsSample

Sample code to demonstrate how to get started with BlazorBindings.Maui in .NET MAUI
C#
6
star
62

XCTTabViewSample

Sample code that demonstrates the use of TabView in a Xamarin.Forms app
C#
6
star
63

MauiPluginAudioSample

Sample code to demonstrate how to work with Plugin.Maui.Audio in .NET MAUI
C#
6
star
64

MAUICustomHandlerSample

Sample code to demonstrate how to customize existing .NET MAUI controls with handlers
C#
6
star
65

MauiCustomizeControlSample

Sample code to demonstrate how to customize a control in .NET MAUI
C#
6
star
66

AzureCustomVisionDemo

Sample Xamarin.Forms app used on an episode of the AI Show
C#
6
star
67

CrossSimpleAudioPlayerSample

Sample repo for a question on StackOverflow about playing a sound in a Xamarin.Forms app
C#
6
star
68

MauiBottomSheetSample

Sample code to demonstrate how to add the The49.Maui.BottomSheet to your .NET MAUI app
C#
6
star
69

XFSQLiteCRUDSample

Sample code to demonstrate basic CRUD actions on SQLite with Xamarin.Forms and .NET MAUI
C#
6
star
70

XFEAccelerometerSample

Sample code on how to use the accelerometer and detect shaking with Xamarin.Essentials and Xamarin.Forms
C#
6
star
71

MauiBlazorAccessNativeSample

Sample code to demonstrate how to access device sensors from Blazor in .NET MAUI
C#
6
star
72

XFBiometricSample

Sample code which demonstrates how to authenticate with fingerprint/Touch ID or face recognition/Face ID in a Xamarin.Forms app
C#
6
star
73

MauiFilePickerSample

Sample code to demonstrate how to pick files in a .NET MAUI app
C#
5
star
74

XFOpenPDFSample

Sample code to demonstrate how to view PDFs in your Xamarin.Forms app
C#
5
star
75

XFXCalendarPluginSample

Sample code to demonstrate the Plugin.XCalendar plugin for Xamarin.Forms
C#
5
star
76

MauiBlazorDialogSample

Sample code to demonstrate how to show a platform-specific dialog from Blazor with .NET MAUI Blazor
C#
5
star
77

XCTSnackbarSample

Sample code to demonstrate how to use SnackBar and Toast with Xamarin.Forms apps and the Xamarin Community Toolkit
C#
5
star
78

XFLocalNotifications

Sample code to demonstrate how to implement local notifications with Xamarin.Forms
C#
5
star
79

MauiCameraMauiBarcodeScanningSample

Sample code to demonstrate how to do barcode scanning with the Camera.MAUI plugin in .NET MAUI
C#
5
star
80

MauiBlazorPlatformTabs

Sample code to demonstrate how to show different Blazor pages in platform tabs with .NET MAUI
CSS
5
star
81

XFEMediaPickerSample

Sample code for showing how to use Xamarin.Essentials MediaPicker
C#
5
star
82

StackNotifier

Get notified about your favorite tags on StackOverflow
JavaScript
5
star
83

HttpConditionalSample

Sample code for my blog post about using HTTP conditional requests
C#
5
star
84

MauiToolkitStatusBarBehaviorSample

Sample code to demonstrate how to change the status bar color in .NET MAUI using the .NET MAUI Community Toolkit
C#
5
star
85

GurCodesListviewGrouping

Code for my episode on how to implement grouping in a ListView
C#
5
star
86

MauiLottieAnimationsSample

Sample code to demonstrate how to add Lottie animations to your .NET MAUI app
C#
5
star
87

XFGenerateBarcodeSample

Sample code for generating barcodes in Xamarin.Forms and ZXing
C#
4
star
88

XFSwipeViewSample

Sample code to demonstrate the SwipeView in Xamarin.Forms
C#
4
star
89

XFSecureStorageSample

Sample code to demonstrate how to implement secure storage in your Xamarin.Forms and .NET MAUI app with Essentials
C#
4
star
90

CarouselViewSample

Sample code for the Xamarin.Forms CarouselView
C#
4
star
91

XFETextToSpeechSample

Sample code on how to implement text-to-speech with Xamarin.Essentials
C#
4
star
92

XFEOpenMapsSample

Sample code to demonstrate how to open the native maps app with Xamarin.Essentials
C#
4
star
93

MauiCSharpMarkupExample

Sample code to demonstrate the C# Markup Extensions for .NET MAUI (and Xamarin.Forms)
C#
4
star
94

MauiFreshMvvmSample

Sample code to demonstrate how to get started with FreshMvvm and .NET MAUI
C#
4
star
95

XFMAUIConvertBehaviorsSample

Sample code to demonstrate how to convert behaviors from Xamarin.Forms to .NET MAUI and how to use behaviors in .NET MAUI
C#
4
star
96

XFFreshMvvmIntroSample

Sample code to demonstrate how to start implementing FreshMvvm in your Xamarin.Forms app
C#
4
star
97

MauiGoogleVisionBarcodeScanningSample

Sample code to demonstrate how to use the Google Vision ML based barcode scanner in .NET MAUI
C#
4
star
98

MauiPlatformCodeSample

Sample code to demonstrate how to write code for a specific platform in .NET MAUI
C#
4
star
99

MauiToolkitFileSaverSample

Sample code to demonstrate the use of the .NET MAUI Community Toolkit FileSaver
C#
4
star
100

XFPlayBackgroundSample

Sample code to demonstrate how to play audio in the background and video Picture-in-Picture on iOS with MediaElement for Xamarin.Forms
C#
4
star