Introduction
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
Azure Blob storage
Azure Blob storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data.
Store any type of unstructured data—including images, videos, audio, documents and backups. You can write error logs also.
Prerequisites
- Visual Studio 2017 or later (Windows or Mac)
- Microsft Azure subscription
Setting up a Xamarin.Forms Project
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
Now, you need to click "Create a new project".
Now, filter by Project Type: Mobile
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
Create a Storage Account in Azure
http://portal.azure.com
In this step, you must create a Storage account service in the Azure portal.
After creating a storage account, check your access keys and connection strings.
Setting up the User Interface
Go to MainPage.Xaml and write the following code.
MainPage.xaml
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- xmlns:local="clr-namespace:XamarinBlob"
- x:Class="XamarinBlob.MainPage">
-
- <StackLayout>
-
- <Image Source="banner1.png" HeightRequest="100"/>
- <Image WidthRequest="200" HeightRequest="150" x:Name="imgChoosed"></Image>
- <Button x:Name="btnPick" Text="Pick" Clicked="BtnPick_Clicked"></Button>
- <Button x:Name="btnStore" Text="Upload" Clicked="BtnStore_Clicked"></Button>
- <Button x:Name="btnGet" Text="Download" Clicked='BtnGet_Clicked'></Button>
- <Button x:Name="btnDelete" Text="Delete" Clicked="BtnDelete_Clicked"></Button>
- </StackLayout>
-
- </ContentPage>
NuGet Packages
Now, add the following NuGet packages.
- Xam.Plugin.Media
- Microsoft.Azure.Storage.Blob
Add Microsoft.Azure.Storage.Blob NuGet
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "Microsoft.Azure.Storage.Blob" and add the resultant package. Remember to install it for each project (.NET Standard, Android, iOS).
Connect your Storage Account
- MediaFile file;
- static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJp**********************ocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";
- static CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
- static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
Pick Files
In this step, I'm going to upload images.
- private async void BtnPick_Clicked(object sender, EventArgs e)
- {
- await CrossMedia.Current.Initialize();
- try
- {
- file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
- {
- PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
- });
- if (file == null)
- return;
- imgChoosed.Source = ImageSource.FromStream(() =>
- {
- var imageStram = file.GetStream();
- return imageStram;
- });
- }
- catch (Exception ex)
- {
- Debug.WriteLine(ex.Message);
- }
- }
Upload Files
Now, write the following code to upload files to Azure blob storage.
- private async void BtnStore_Clicked(object sender, EventArgs e)
- {
-
- string filePath = file.Path;
- string fileName = Path.GetFileName(filePath);
- await cloudBlobContainer.CreateIfNotExistsAsync();
-
- await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions
- {
- PublicAccess = BlobContainerPublicAccessType.Blob
- });
- var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
- await UploadImage(blockBlob, filePath);
- }
-
- private static async Task UploadImage(CloudBlockBlob blob, string filePath)
- {
- using (var fileStream = File.OpenRead(filePath))
- {
- await blob.UploadFromStreamAsync(fileStream);
- }
- }
Download Files
Use the following code to download files from Azure blob storage.
- private async void BtnGet_Clicked(object sender, EventArgs e)
- {
- string filePath = file.Path;
- string fileName = Path.GetFileName(filePath);
- var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
- await DownloadImage(blockBlob, filePath);
- }
-
- private static async Task DownloadImage(CloudBlockBlob blob, string filePath)
- {
- if (blob.ExistsAsync().Result)
- {
- await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);
- }
- }
Delete Files
Use the following code to Delete files from Azure blob storage.
- private async void BtnDelete_Clicked(object sender, EventArgs e)
- {
- var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
- await DeleteImage(blockBlob);
- }
-
-
- private static async Task DeleteImage(CloudBlockBlob blob)
- {
- if (blob.ExistsAsync().Result)
- {
- await blob.DeleteAsync();
- }
- }
Check out Full Code
MainPage.xaml.cs
- using Xamarin.Forms;
- using Microsoft.Azure.Storage;
- using Microsoft.Azure.Storage.Blob;
- using System.IO;
-
- namespace XamarinBlob
- {
- public partial class MainPage : ContentPage
- {
- MediaFile file;
- static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJphtzmjnBy0RoyQLgRC8WEvh6ecc9RbWocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";
- static CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
- static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
- static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
-
- public MainPage()
- {
- InitializeComponent();
- }
-
- private async void BtnPick_Clicked(object sender, EventArgs e)
- {
- await CrossMedia.Current.Initialize();
- try
- {
- file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
- {
- PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
- });
- if (file == null)
- return;
- imgChoosed.Source = ImageSource.FromStream(() =>
- {
- var imageStram = file.GetStream();
- return imageStram;
- });
- }
- catch (Exception ex)
- {
- Debug.WriteLine(ex.Message);
- }
- }
-
- private async void BtnStore_Clicked(object sender, EventArgs e)
- {
-
- string filePath = file.Path;
- string fileName = Path.GetFileName(filePath);
- await cloudBlobContainer.CreateIfNotExistsAsync();
-
- await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions
- {
- PublicAccess = BlobContainerPublicAccessType.Blob
- });
- var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
- await UploadImage(blockBlob, filePath);
- }
-
- private async void BtnGet_Clicked(object sender, EventArgs e)
- {
- string filePath = file.Path;
- string fileName = Path.GetFileName(filePath);
- var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
- await DownloadImage(blockBlob, filePath);
- }
-
- private async void BtnDelete_Clicked(object sender, EventArgs e)
- {
- var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
- await DeleteImage(blockBlob);
- }
-
- private static async Task UploadImage(CloudBlockBlob blob, string filePath)
- {
- using (var fileStream = File.OpenRead(filePath))
- {
- await blob.UploadFromStreamAsync(fileStream);
- }
- }
-
- private static async Task DownloadImage(CloudBlockBlob blob, string filePath)
- {
- if (blob.ExistsAsync().Result)
- {
- await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);
- }
- }
-
- private static async Task DeleteImage(CloudBlockBlob blob)
- {
- if (blob.ExistsAsync().Result)
- {
- await blob.DeleteAsync();
- }
- }
- }
- }
Click the "Play" button to try it out.
I hope you have understood how to use Azure Blob Storage in Xamarin.Forms.
Thanks for reading. Please share your comments and feedback. Happy Coding :)