How to Read and Write Barcode on Android in .NET MAUI

This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to How to Read and Write Barcode on Android in .NET MAUI

.NET MAUI (Multi-platform App UI) is the successor to Xamarin.Forms, enabling developers to build cross-platform applications for Android, iOS, macOS, and Windows using .NET. It streamlines the development process by allowing the creation of native user interfaces that work seamlessly across multiple platforms.

The BarCode.Android package brings barcode support to Android!

IronBarcode Android Package

The BarCode.Android package enables barcode features on Android devices via .NET cross-platform projects. The vanilla BarCode package is not needed.

Install-Package BarCode.Android
C# NuGet Library for PDF

Install with NuGet

Install-Package BarCode.Android

Create a .NET MAUI Project

Open Visual Studio and click on "Create a new project". Search for MAUI, select .NET MAUI App and "Next".

Include the BarCode.Android Library

The library can be added in various ways. The easiest is perhaps by using NuGet.

  1. Inside Visual Studio, right-click on "Dependencies" and select "Manage NuGet Packages ...".
  2. Select the "Browse" tab and search for "BarCode.Android".
  3. Select the "BarCode.Android" package and click on "Install".

To prevent issues with other platforms, modify the csproj file to only include the package when targeting the Android platform. In order to do so:

  1. Right-click on the *.csproj file for your project and select "Edit Project File".
  2. Create a new ItemGroup element as such:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. Move the "BarCode.Android" PackageReference inside the ItemGroup we just created.

The above steps will prevent the "BarCode.Android" package from being used on platforms such as iOS. For that purpose, install BarCode.iOS instead.

Configure the Android Bundle

For Android to work, you need to configure the Android bundle settings. In your ".csproj" file, add the following entry to specify the configuration file for the Android bundle:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

Create a file named "BundleConfig.json" in the root directory of the project. This JSON file contains the required settings for the Android bundle, which are crucial for the library's functionality.

{
    "optimizations": {
        "uncompress_native_libraries": {}
    }
}

This configuration ensures that native libraries are uncompressed, which is a necessary step for the library to function properly in the Android environment.

Design the App Interface

Update the XAML file to allow users to input values for generating barcodes and QR codes. Additionally, add a button to choose a document for barcode reading. Here’s an example:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiAndroid.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
            Text="Read Barcode"
            Clicked="ReadBarcode"
            Grid.Row="0"
            HorizontalOptions="Center"
            Margin="20, 20, 20, 10"/>
        <ScrollView
            Grid.Row="1"
            BackgroundColor="LightGray"
            Padding="10"
            Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="IronBarcodeMauiAndroid.MainPage">

    <VerticalStackLayout Padding="20">
        <HorizontalStackLayout>
            <CheckBox x:Name="generatePdfCheckBox" IsChecked="{Binding IsGeneratePdfChecked}" />
            <Label Text="PDF (unchecked for PNG)" VerticalOptions="Center"/>
        </HorizontalStackLayout>

        <Entry x:Name="barcodeInput" Placeholder="Enter barcode value..." />
        <Button Text="Generate and save barcode" Clicked="WriteBarcode" />

        <Entry x:Name="qrInput" Placeholder="Enter QR code value..." />
        <Button Text="Generate and save QR code" Clicked="WriteQRcode" />

        <Button
            Text="Read Barcode"
            Clicked="ReadBarcode"
            Grid.Row="0"
            HorizontalOptions="Center"
            Margin="20, 20, 20, 10"/>
        <ScrollView
            Grid.Row="1"
            BackgroundColor="LightGray"
            Padding="10"
            Margin="10, 10, 10, 30">
            <Label x:Name="OutputText"/>
        </ScrollView>
    </VerticalStackLayout>

</ContentPage>
XML

Read and Write Barcodes

From the MainPage.xaml code above, we can see that the checkbox determines whether the generated barcode and QR code should be in PDF format. Next, we set the license key. Please use either a trial or paid license key for this step.

The code checks and retrieves the value from the barcodeInput variable, then uses the CreateBarcode method to generate the barcode. Finally, it calls the SaveToDownloadsAsync method, which saves the file appropriately for both Android and iOS.

On iOS, a custom file path is required to export the document to the Files application.

using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            // Set the license key for IronBarcode, replace with your actual license key.
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    // Create a barcode from the text input with the EAN13 encoding.
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated barcode to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    // Create a QR code from the text input.
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated QR code to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void ReadBarcode(object sender, EventArgs e)
        {
            try
            {
                var options = new PickOptions
                {
                    PickerTitle = "Please select a file"
                };
                var file = await FilePicker.PickAsync(options);

                OutputText.Text = "";

                if (file != null)
                {
                    using var stream = await file.OpenReadAsync();

                    BarcodeResults result;

                    if (file.ContentType.Contains("image"))
                    {
                        // Read barcodes from an image file.
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        // Read barcodes from a PDF file.
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    // Retrieve and format the barcode reading results.
                    result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
            var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);

            try
            {
                // Create the directory if it doesn't exist.
                if (!Directory.Exists(downloadsPath.AbsolutePath))
                {
                    Directory.CreateDirectory(downloadsPath.AbsolutePath);
                }

                // Save the file to the Downloads folder.
                await File.WriteAllBytesAsync(filePath, fileData);
            }
            catch (Exception ex)
            {
                // Log errors if file saving fails.
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
        }
    }
}
using IronBarCode;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Essentials;

namespace IronBarcodeMauiAndroid
{
    public partial class MainPage : ContentPage
    {
        public bool IsGeneratePdfChecked
        {
            get => generatePdfCheckBox.IsChecked;
            set
            {
                generatePdfCheckBox.IsChecked = value;
            }
        }

        public MainPage()
        {
            InitializeComponent();
            // Set the license key for IronBarcode, replace with your actual license key.
            License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
        }

        private async void WriteBarcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(barcodeInput.Text))
                {
                    // Create a barcode from the text input with the EAN13 encoding.
                    var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated barcode to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void WriteQRcode(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(qrInput.Text))
                {
                    // Create a QR code from the text input.
                    var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);

                    // Determine the file extension and data format based on the checkbox state.
                    string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
                    string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
                    byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();

                    // Save the generated QR code to the Downloads folder.
                    await SaveToDownloadsAsync(fileData, fileName);

                    await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        private async void ReadBarcode(object sender, EventArgs e)
        {
            try
            {
                var options = new PickOptions
                {
                    PickerTitle = "Please select a file"
                };
                var file = await FilePicker.PickAsync(options);

                OutputText.Text = "";

                if (file != null)
                {
                    using var stream = await file.OpenReadAsync();

                    BarcodeResults result;

                    if (file.ContentType.Contains("image"))
                    {
                        // Read barcodes from an image file.
                        result = BarcodeReader.Read(stream);
                    }
                    else
                    {
                        // Read barcodes from a PDF file.
                        result = BarcodeReader.ReadPdf(stream);
                    }

                    string barcodeResult = "";
                    int count = 1;

                    // Retrieve and format the barcode reading results.
                    result.ForEach(x => { barcodeResult += $"Barcode {count}: {x.Value}\n"; count++; });

                    OutputText.Text = barcodeResult;
                }
            }
            catch (Exception ex)
            {
                // Handle exceptions and log the error.
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
        {
            var downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
            var filePath = Path.Combine(downloadsPath.AbsolutePath, fileName);

            try
            {
                // Create the directory if it doesn't exist.
                if (!Directory.Exists(downloadsPath.AbsolutePath))
                {
                    Directory.CreateDirectory(downloadsPath.AbsolutePath);
                }

                // Save the file to the Downloads folder.
                await File.WriteAllBytesAsync(filePath, fileData);
            }
            catch (Exception ex)
            {
                // Log errors if file saving fails.
                System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
            }
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials

Namespace IronBarcodeMauiAndroid
	Partial Public Class MainPage
		Inherits ContentPage

		Public Property IsGeneratePdfChecked() As Boolean
			Get
				Return generatePdfCheckBox.IsChecked
			End Get
			Set(ByVal value As Boolean)
				generatePdfCheckBox.IsChecked = value
			End Set
		End Property

		Public Sub New()
			InitializeComponent()
			' Set the license key for IronBarcode, replace with your actual license key.
			License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
		End Sub

		Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(barcodeInput.Text) Then
					' Create a barcode from the text input with the EAN13 encoding.
					Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)

					' Determine the file extension and data format based on the checkbox state.
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())

					' Save the generated barcode to the Downloads folder.
					Await SaveToDownloadsAsync(fileData, fileName)

					Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(qrInput.Text) Then
					' Create a QR code from the text input.
					Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)

					' Determine the file extension and data format based on the checkbox state.
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(IsGeneratePdfChecked, barcode.ToPdfBinaryData(), barcode.ToPngBinaryData())

					' Save the generated QR code to the Downloads folder.
					Await SaveToDownloadsAsync(fileData, fileName)

					Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
				Dim file = Await FilePicker.PickAsync(options)

				OutputText.Text = ""

				If file IsNot Nothing Then
					Dim stream = Await file.OpenReadAsync()

					Dim result As BarcodeResults

					If file.ContentType.Contains("image") Then
						' Read barcodes from an image file.
						result = BarcodeReader.Read(stream)
					Else
						' Read barcodes from a PDF file.
						result = BarcodeReader.ReadPdf(stream)
					End If

					Dim barcodeResult As String = ""
					Dim count As Integer = 1

					' Retrieve and format the barcode reading results.
					result.ForEach(Sub(x)
						barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
						count += 1
					End Sub)

					OutputText.Text = barcodeResult
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
			Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
			Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)

			Try
				' Create the directory if it doesn't exist.
				If Not Directory.Exists(downloadsPath.AbsolutePath) Then
					Directory.CreateDirectory(downloadsPath.AbsolutePath)
				End If

				' Save the file to the Downloads folder.
				Await File.WriteAllBytesAsync(filePath, fileData)
			Catch ex As Exception
				' Log errors if file saving fails.
				System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
			End Try
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

Run the Project

This will show you how to run the project and use the barcode feature.

Execute .NET MAUI App project

Download .NET MAUI App Project

You can download the complete code for this guide. It comes as a zipped file that you can open in Visual Studio as a .NET MAUI App project.

Click here to download the project.

Preguntas Frecuentes

¿Cómo puedo crear y escanear códigos de barras en una aplicación .NET MAUI para Android?

Puedes usar el paquete BarCode.Android dentro de un proyecto .NET MAUI para crear y escanear códigos de barras en dispositivos Android. Esto implica configurar el paquete a través de NuGet en Visual Studio e implementar funcionalidades de código de barras usando métodos proporcionados como WriteBarcode y ReadBarcode.

¿Qué pasos son necesarios para configurar la funcionalidad de código de barras para Android en un proyecto .NET MAUI?

Para configurar la funcionalidad de código de barras en un proyecto .NET MAUI, instala el paquete BarCode.Android usando NuGet, configura tu archivo .csproj para incluir condicionalmente el paquete para Android y asegúrate de que tu paquete de Android esté configurado a través de un archivo BundleConfig.json.

¿Cómo configuro el archivo .csproj para incluir la funcionalidad de código de barras solo para Android?

Edita el archivo .csproj agregando un con una condición que apunte a Android. Incluye el paquete BarCode.Android dentro de este grupo para garantizar que la funcionalidad de código de barras se agregue solo para las compilaciones de Android.

¿Cuál es el propósito de usar un archivo BundleConfig.json en proyectos de Android?

El archivo BundleConfig.json se utiliza para configurar la configuración del paquete de Android, asegurando que las bibliotecas nativas no estén comprimidas. Esto es esencial para que la biblioteca de código de barras funcione correctamente en dispositivos Android.

¿Cómo puedo diseñar una interfaz para operaciones de códigos de barras en una aplicación .NET MAUI?

Diseña la interfaz de la aplicación usando XAML para permitir a los usuarios ingresar datos para generar códigos de barras y códigos QR. Incluye botones para seleccionar documentos de los cuales leer códigos de barras y para generar, guardar y escanear códigos de barras.

¿Qué métodos se usan en C# para generar y leer códigos de barras en una aplicación?

En una aplicación .NET MAUI, utiliza métodos como WriteBarcode, WriteQRcode, y ReadBarcode para generar códigos de barras, crear códigos QR y leer códigos de barras de archivos, respectivamente.

¿Cómo probar características de código de barras en mi app .NET MAUI?

Después de configurar tu proyecto con las configuraciones necesarias y las implementaciones de código de barras, puedes probar las características ejecutando el proyecto en un dispositivo Android o emulador a través de Visual Studio.

¿Dónde puedo encontrar un proyecto completo de aplicación .NET MAUI con funcionalidades de códigos de barras?

Un proyecto completo de aplicación .NET MAUI con funcionalidades de códigos de barras puede descargarse en formato comprimido desde el sitio web de IronBarcode. Este proyecto puede abrirse en Visual Studio para una mayor exploración y personalización.

¿Se requiere una licencia para usar la biblioteca de códigos de barras en mi proyecto de Android?

Sí, el uso de la biblioteca de códigos de barras en tu proyecto requiere una clave de licencia de prueba o pagada. Necesitas ingresar esta clave en el constructor de MainPage para activar las características de la biblioteca.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,935,276 | Versión: 2025.11 recién lanzado