Want to pick files from the device and visualize them in your mobile and desktop applications? No problem! It’s more than easy with Xamarin.Essentials and Telerik UI for Xamarin controls.
In this blog post, we will go through how to use the FilePicker API. We will implement a sample UI for picking images, pdf documents, and selecting multiple images. But what’s next? π§ We want to visualize these files in our application, so we need proper controls, right? And the Telerik UI for Xamarin suite comes in to help us! π
The FilePicker allows us to pick a single or multiple file from the device more than easily. We need a single NuGet package installed to our existing project or new project—Xamarin.Essentials NuGet package.
1. Make sure the Xamarin.Essentials is initialized inside the OnCreate() method of the MainActivity.cs file of the Android project:
Xamarin.Essentials.Platform.Init(
this
, savedInstanceState);
2. For handling runtime permissions on Android, inside the MainActivity.cs file—override the OnRequestPermissionsResult() method:
public
override
void
OnRequestPermissionsResult(
int
requestCode,
string
[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base
.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
3. Grant permissions to read data from the external storage. We can use one of the following options:
[assembly: UsesPermission(Android.Manifest.Permission.ReadExternalStorage)]
<
uses-permission
android:name
=
"android.permission.READ_EXTERNAL_STORAGE"
/>
Android permissions popup:
They don’t require additional setup.
FilePicker class gives us two methods for picking file(s):
Both methods have a parameter PickOptions for specifying additional information like:
var seletedImage = await FilePicker.PickAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select an image"
});
Of course, we can specify custom file types per platform. For example, if we want the user to be able to pick a .txt file on iOS, a .pdf file on Android, and .txt/.pdf/.docx files on UWP, we’d use the following simple code:
var customFileType =
new
FilePickerFileType(
new
Dictionary<DevicePlatform, IEnumerable<
string
>>
{
{ DevicePlatform.iOS,
new
[] {
".txt"
} },
{ DevicePlatform.Android,
new
[] {
".png"
} },
{ DevicePlatform.UWP,
new
[] {
".docx"
,
".txt"
,
".pdf"
} },
});
var options =
new
PickOptions
{
PickerTitle =
"Please select a comic file"
,
FileTypes = customFileType,
};
var result = await FilePicker.PickAsync(options);
We will use PickAsync() and PickMultipleAsync() methods in our demo.π
β We must add the following namespace where the FilePicker API is used:
using
Xamarin.Essentials;
This is what the FilePicker demo looks like:
The demo uses the following Telerik UI for Xamarin controls:
I have added the Telerik UI for Xamarin controls to the project using the Telerik NuGet Server.
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
ContentPage
xmlns
=
"http://xamarin.com/schemas/2014/forms"
xmlns:telerikInput
=
"clr-namespace:Telerik.XamarinForms.Input;assembly=Telerik.XamarinForms.Input"
xmlns:telerikPrimitives
=
"clr-namespace:Telerik.XamarinForms.Primitives;assembly=Telerik.XamarinForms.Primitives"
xmlns:telerikPdfViewer
=
"clr-namespace:Telerik.XamarinForms.PdfViewer;assembly=Telerik.XamarinForms.PdfViewer"
xmlns:telerikDataControls
=
"clr-namespace:Telerik.XamarinForms.DataControls;assembly=Telerik.XamarinForms.DataControls"
xmlns:telerikListView
=
"clr-namespace:Telerik.XamarinForms.DataControls.ListView;assembly=Telerik.XamarinForms.DataControls"
x:Class
=
"FilePickerDemo.MainPage"
>
<
ContentPage.Resources
>
<
ResourceDictionary
>
<
Style
TargetType
=
"telerikPrimitives:TabViewHeaderItem"
>
<
Setter
Property
=
"TextColor"
Value
=
"Black"
/>
<
Setter
Property
=
"SelectedColor"
Value
=
"#0E88F2"
/>
</
Style
>
<
Style
TargetType
=
"telerikInput:RadButton"
>
<
Setter
Property
=
"WidthRequest"
Value
=
"100"
/>
<
Setter
Property
=
"CornerRadius"
Value
=
"15"
/>
<
Setter
Property
=
"Margin"
Value
=
"10"
/>
<
Setter
Property
=
"TextColor"
Value
=
"White"
/>
<
Setter
Property
=
"BackgroundColor"
Value
=
"#0E88F2"
/>
</
Style
>
</
ResourceDictionary
>
</
ContentPage.Resources
>
<
Grid
RowDefinitions
=
"Auto,*"
>
<
Label
Text
=
"Welcome to FilePicker Demo"
HorizontalTextAlignment
=
"Center"
TextColor
=
"Black"
FontSize
=
"36"
/>
<
telerikPrimitives:RadTabView
Grid.Row
=
"1"
IsContentPreserved
=
"True"
IsContentSwipingEnabled
=
"False"
>
<
telerikPrimitives:RadTabView.Items
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Image"
>
<
telerikPrimitives:TabViewItem.Content
>
<
StackLayout
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Image"
Clicked
=
"OnPickImageClicked"
/>
<
Label
x:Name
=
"PickedImageInfo"
FontSize
=
"16"
Margin
=
"10"
/>
<
Image
x:Name
=
"image"
HeightRequest
=
"200"
WidthRequest
=
"200"
/>
</
StackLayout
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Pdf"
>
<
telerikPrimitives:TabViewItem.Content
>
<
Grid
RowDefinitions
=
"Auto,*"
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Pdf Document"
Clicked
=
"OnPickPdfClicked"
/>
<
telerikPdfViewer:RadPdfViewer
x:Name
=
"pdfViewer"
Grid.Row
=
"1"
BackgroundColor
=
"Transparent"
/>
</
Grid
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
<
telerikPrimitives:TabViewItem
HeaderText
=
"Pick Multiple Images"
>
<
telerikPrimitives:TabViewItem.Content
>
<
Grid
RowDefinitions
=
"Auto,*"
Margin
=
"10"
>
<
telerikInput:RadButton
Text
=
"Pick Multiple Images"
Clicked
=
"OnPickMultipleImagesClicked"
/>
<
telerikDataControls:RadListView
x:Name
=
"listView"
Grid.Row
=
"1"
>
<
telerikDataControls:RadListView.ItemTemplate
>
<
DataTemplate
>
<
telerikListView:ListViewTemplateCell
>
<
telerikListView:ListViewTemplateCell.View
>
<
StackLayout
Margin
=
"10"
>
<
Image
HeightRequest
=
"100"
WidthRequest
=
"100"
VerticalOptions
=
"Center"
Source
=
"{Binding .}"
/>
</
StackLayout
>
</
telerikListView:ListViewTemplateCell.View
>
</
telerikListView:ListViewTemplateCell
>
</
DataTemplate
>
</
telerikDataControls:RadListView.ItemTemplate
>
</
telerikDataControls:RadListView
>
</
Grid
>
</
telerikPrimitives:TabViewItem.Content
>
</
telerikPrimitives:TabViewItem
>
</
telerikPrimitives:RadTabView.Items
>
</
telerikPrimitives:RadTabView
>
</
Grid
>
</
ContentPage
>
As you can see in the XAML, we have a TabView control with three different TabViewItems. Next, let me take you through what each TabViewItem does.
The first tab is for picking a single image from the device. When the Button is clicked, we can pick an image from the device and visualize it in the Image control. Here is the OnPickImageClicked() implemetation:
private
async
void
OnPickImageClicked(
object
sender, System.EventArgs e)
{
try
{
var seletedImage = await FilePicker.PickAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select an image"
});
if
(seletedImage !=
null
)
{
var data = await seletedImage.OpenReadAsync();
PickedImageInfo.Text = $
"The filename: {seletedImage.FileName} and file type: {seletedImage.ContentType}"
;
image.Source = ImageSource.FromStream(() => data);
}
return
;
}
catch
(Exception)
{
}
}
The second tab is for picking a pdf document and visualizing it in the RadPdfViewer. Here is the OnPickPdfClicked() implementation.
private
async
void
OnPickPdfClicked(
object
sender, System.EventArgs e)
{
try
{
var selectedFile = await FilePicker.PickAsync(
new PickOptions
{
FileTypes = FilePickerFileType.Pdf,
PickerTitle =
"Select a pdf"
});
if
(selectedFile !=
null
)
{
var data = await selectedFile.OpenReadAsync();
PdfFormatProvider provider =
new
PdfFormatProvider();
RadFixedDocument document = provider.Import(data);
pdfViewer.Source = document;
pdfViewer.IsVisible =
true;
}
return
;
}
catch
(Exception)
{
}
}
The third tab is for multiple image selection. When the button is clicked, we can select multiple images from the device and visualize them in the RadListView control. Here is the OnPickMultipleImagesClicked() implementation:
private
async
void
OnPickMultipleImagesClicked(
object
sender, EventArgs e)
{
try
{
var selectedImage = await FilePicker.PickMultipleAsync(
new
PickOptions
{
FileTypes = FilePickerFileType.Images,
PickerTitle =
"Select images"
});
var imageList =
new
List<ImageSource>();
if
(selectedImage !=
null
)
{
foreach
(var selected
in
selectedImage)
{
var data = await selected.OpenReadAsync();
imageList.Add(ImageSource.FromStream(()=>data));
}
listView.ItemsSource = imageList;
}
return
;
}
catch
(Exception)
{
}
}
You can easily pick HTML documents and then visualize them in your desktop and mobile apps using the Telerik RichTextEditor for Xamarin.
We would love to hear what you think, so should you have any questions and/or comments, please share them in our Telerik UI for Xamarin Feedback Portal.
If you are new to Telerik UI for Xamarin, you can learn more about it via the product page. It comes with a 30-day free trial, giving you some time to explore the toolkit and consider using it for your current or upcoming Xamarin development.
We would also like to share with you our preview UI components for .NET MAUI—Telerik UI for .NET MAUI. You can review the available controls and their features in our Telerik UI for .NET MAUI Demo Application.
Happy coding with our controls! π§‘
Dobrinka Yordanova is a Technical Support Engineer, part of the Progress Telerik UI for Xamarin & UWP team in Sofia, Bulgaria. She holds a master's degree in Computer Systems and Technologies. Her passion is traveling around the world and exploring multicultural environments. In her spare time she likes making sushi, playing console games and hanging out with friends.