Cómo leer y escanear código de barras en C# usando NET MAUI

.NET MAUI Barcode Scanner

This article was translated from English: Does it need improvement?
Translated
View the article in English

Introduction

.NET MAUI (.NET Multi-platform App UI) is a cross-platform framework to seamlessly create cross-platform applications in a single codebase. For example, you can easily create Microsoft Windows, iOS, and Android applications in one project. What separates it from other platforms, frameworks, and libraries is the way it lets the developer community use the native controls in their projects and provides them with extra components. As a result, developers can use these pre-made components and services to build the applications more quickly without writing every aspect of the code from scratch.

In this article, we'll explain how to integrate IronBarcode in a .NET MAUI Windows app to scan a barcode or QR code.

IronBarcode: C# Barcode Library

To read barcodes in our application, we'll be using the IronBarcode .NET library. It provides a robust and simple API for reading barcodes, allowing for development without any hassle or barcode domain knowledge. It can be easily installed with the NuGet package manager.

IronBarcode supports a multitude of barcodes formats for reading, including Code 39, Code 128, PDF417, among many others. You can read from a variety of data formats such as image files, memory streams, and PDFs.

Steps to Read Barcodes in a .NET MAUI App

Follow these steps to read a barcode in a .NET MAUI app.

Prerequisites

  1. Visual Studio 2022
  2. A .NET MAUI project in Visual Studio

Install IronBarcode Library

We can install the IronBarcode library using the NuGet Package Manager Console. To open this console in Visual Studio, navigate to Tools > NuGet Package Manager > Package Manager Console. Then, write the following command in the console:

Install-Package BarCode

This console command will download the latest version of the IronBarcode library in the MAUI project. Alternatively, you could also search for the latest version of the NuGet package on theNuGet website.

Front-End

The first step will be to create the front-end design. For this, we will create a layout that consists of two buttons, one text area, and one image box. One button will be used to select the barcode, and another will copy the text of the barcode. The Image box will show the selected image.

Replace the content in MainPage.xaml file with the following:

<?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="MAUI_Barcode.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Editor
                x:Name="outputText"
                Placeholder="Output text"
                HeightRequest="100"
                WidthRequest="500" />
            <Button
                x:Name="copyText"
                Text="Copy"
                SemanticProperties.Hint="Copy Text"
                WidthRequest="150"
                Clicked="CopyEditorText"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</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="MAUI_Barcode.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Button
                x:Name="ImageSelect"
                Text="Select Barcode"
                SemanticProperties.Hint="Select Image"
                Clicked="SelectBarcode"
                HorizontalOptions="Center" />
            <Image
                x:Name="barcodeImage"
                SemanticProperties.Description="Selected Barcode"
                HeightRequest="200"
                HorizontalOptions="Center" />
            <Editor
                x:Name="outputText"
                Placeholder="Output text"
                HeightRequest="100"
                WidthRequest="500" />
            <Button
                x:Name="copyText"
                Text="Copy"
                SemanticProperties.Hint="Copy Text"
                WidthRequest="150"
                Clicked="CopyEditorText"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>
XML

All elements are in a vertical stack with the center position. You can change it according to your preference.

Barcode Scanning using IronBarcode

This section will describe the code for scanning barcodes using the IronBarcode library. First, we'll use a FilePicker to select the file and specify the file type for the image. After that, we will use the FullPath property to retrieve the image file's path and then set the source of the image box to the FullPath value. Finally, we will use the path value in the Read function of the BarcodeReader to retrieve the text.

private async void SelectBarcode(object sender, EventArgs e)
{
    // Use FilePicker to allow the user to select an image file.
    var images = await FilePicker.Default.PickAsync(new PickOptions
    {
        PickerTitle = "Pick image",
        FileTypes = FilePickerFileType.Images
    });

    // Get the full path of the selected image file.
    var imageSource = images.FullPath.ToString();

    // Set the source of the Image view to the selected image's path.
    barcodeImage.Source = imageSource;

    // Use IronBarcode to read the barcode from the image file and get the first result.
    var result = BarcodeReader.Read(imageSource).First().Text;

    // Display the read result in the Editor.
    outputText.Text = result;
}
private async void SelectBarcode(object sender, EventArgs e)
{
    // Use FilePicker to allow the user to select an image file.
    var images = await FilePicker.Default.PickAsync(new PickOptions
    {
        PickerTitle = "Pick image",
        FileTypes = FilePickerFileType.Images
    });

    // Get the full path of the selected image file.
    var imageSource = images.FullPath.ToString();

    // Set the source of the Image view to the selected image's path.
    barcodeImage.Source = imageSource;

    // Use IronBarcode to read the barcode from the image file and get the first result.
    var result = BarcodeReader.Read(imageSource).First().Text;

    // Display the read result in the Editor.
    outputText.Text = result;
}
Private Async Sub SelectBarcode(ByVal sender As Object, ByVal e As EventArgs)
	' Use FilePicker to allow the user to select an image file.
	Dim images = Await FilePicker.Default.PickAsync(New PickOptions With {
		.PickerTitle = "Pick image",
		.FileTypes = FilePickerFileType.Images
	})

	' Get the full path of the selected image file.
	Dim imageSource = images.FullPath.ToString()

	' Set the source of the Image view to the selected image's path.
	barcodeImage.Source = imageSource

	' Use IronBarcode to read the barcode from the image file and get the first result.
	Dim result = BarcodeReader.Read(imageSource).First().Text

	' Display the read result in the Editor.
	outputText.Text = result
End Sub
$vbLabelText   $csharpLabel

The code shown below will be used to copy the text editor's text and display an alert message to the user that the text is copied.

private async void CopyEditorText(object sender, EventArgs e)
{
    // Copy the text from the Editor to the clipboard.
    await Clipboard.SetTextAsync(outputText.Text);

    // Show a success message to the user.
    await DisplayAlert("Success", "Text is copied!", "OK");
}
private async void CopyEditorText(object sender, EventArgs e)
{
    // Copy the text from the Editor to the clipboard.
    await Clipboard.SetTextAsync(outputText.Text);

    // Show a success message to the user.
    await DisplayAlert("Success", "Text is copied!", "OK");
}
Private Async Sub CopyEditorText(ByVal sender As Object, ByVal e As EventArgs)
	' Copy the text from the Editor to the clipboard.
	Await Clipboard.SetTextAsync(outputText.Text)

	' Show a success message to the user.
	Await DisplayAlert("Success", "Text is copied!", "OK")
End Sub
$vbLabelText   $csharpLabel

You can find the project source code in this article on GitHub.

Output

After running the project, you'll see the following output. The image is not showing because it is not selected yet.

.NET MAUI Barcode Scanner Tutorial Using IronBarcode - Figure 1: Output when no image is selected

Output when no image is selected

When the barcode is selected, it'll show like the below screenshot, and the output text of the QR Code will be shown in the editor.

.NET MAUI Barcode Scanner Tutorial Using IronBarcode - Figure 2: Output after image is selected

Output after image is selected

Clicking the Copy button will trigger the alert window mentioned before to appear.

.NET MAUI Barcode Scanner Tutorial Using IronBarcode - Figure 3: Copy alert

Copy alert

Conclusion

In this article, we explained how we can read barcodes in a .NET MAUI application using IronBarcode. As a QR code reader, IronBarcode performs very well—it provides the exact output as expected. Moreover, it can read barcodes that are difficult to read. You can also create and customize barcodes by using different fonts. Get more tutorial posts regarding IronBarcode from this link.

IronBarcode must be licensed for development and commercial use. You can find more information on licensing here.

Preguntas Frecuentes

¿Cómo puedo escanear códigos QR en una aplicación .NET MAUI?

Puedes escanear códigos QR en una aplicación .NET MAUI usando la biblioteca IronBarcode. Instala la biblioteca a través del Administrador de Paquetes de NuGet en Visual Studio y utiliza el método BarcodeReader.Read para extraer texto de un archivo de imagen seleccionado.

¿Cuál es el proceso para instalar IronBarcode en un proyecto .NET MAUI?

Para instalar IronBarcode en un proyecto .NET MAUI, abre la Consola del Administrador de Paquetes de NuGet en Visual Studio y ejecuta el comando Install-Package Barcode para descargar e instalar la biblioteca.

¿Qué formatos de código de barras se pueden leer usando la biblioteca IronBarcode?

IronBarcode soporta una variedad de formatos de código de barras, incluyendo códigos QR, Code 39, Code 128, PDF417, y más, permitiendo capacidades de lectura de códigos de barras versátiles en tus aplicaciones.

¿Cómo diseño la interfaz para una aplicación escáner de códigos de barras en .NET MAUI?

En .NET MAUI, la interfaz para una aplicación escáner de códigos de barras se puede diseñar usando XAML. Típicamente incluye un diseño con botones, un área de texto y un cuadro de imagen, que se pueden definir en el archivo MainPage.xaml.

¿Cómo puedo copiar el texto de un código de barras escaneado al portapapeles en una aplicación .NET MAUI?

Usa el método Clipboard.SetTextAsync en tu aplicación .NET MAUI para copiar el texto del código de barras escaneado al portapapeles. Este método puede ser activado por un clic en un botón, mostrando una alerta para confirmar la acción.

¿Es posible personalizar las apariencias de los códigos de barras en .NET MAUI con IronBarcode?

Sí, IronBarcode permite la personalización de las apariencias de los códigos de barras proporcionando opciones para alterar fuentes, colores y estilos, permitiendo la creación de códigos de barras visualmente adaptados.

¿Necesito una licencia para usar IronBarcode en aplicaciones comerciales?

Sí, se requiere una licencia para usar IronBarcode tanto para desarrollo como para propósitos comerciales. Los detalles de licencia y opciones están disponibles en el sitio web de IronBarcode.

¿Dónde puedo acceder al código fuente del tutorial del escáner de códigos de barras de .NET MAUI?

El código fuente del tutorial del escáner de códigos de barras de .NET MAUI está disponible en GitHub. Un enlace al repositorio se proporciona en el artículo para facilitar el acceso.

¿Cómo mejora IronBarcode el escaneo de códigos de barras en aplicaciones .NET MAUI?

IronBarcode mejora el escaneo de códigos de barras en aplicaciones .NET MAUI proporcionando una API robusta que soporta múltiples formatos de códigos de barras y una integración fluida con proyectos .NET MAUI, asegurando una lectura de códigos de barras eficiente y precisa.

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