Barcodes lesen und schreiben auf Android in .NET MAUI
.NET MAUI (Multi-platform App UI) ist der Nachfolger von Xamarin.Forms und ermöglicht es Entwicklern, plattformübergreifende Anwendungen für Android, iOS, macOS und Windows mit .NET zu erstellen. Es vereinfacht den Entwicklungsprozess, indem es die Erstellung von nativen Benutzeroberflächen ermöglicht, die nahtlos über mehrere Plattformen hinweg funktionieren.
Das Paket BarCode.Android bringt Barcode-Unterstützung auf Android!
Barcodes lesen und schreiben auf Android in .NET MAUI
IronBarcode Android Paket
Das Paket BarCode.Android ermöglicht Barcode-Funktionen auf Android-Geräten über plattformübergreifende .NET -Projekte. Das Standard-BarCode-Paket ist nicht erforderlich.
Installieren-Paket BarCode.Android
Installieren-Paket BarCode.Android
Erstellen Sie ein .NET MAUI Projekt
Öffnen Sie Visual Studio und klicken Sie auf "Neues Projekt erstellen". Nach MAUI suchen, .NET MAUI App auswählen und auf 'Weiter' klicken.
Binden Sie die BarCode.Android Bibliothek ein
Die Bibliothek kann auf verschiedene Weise hinzugefügt werden. Die einfachste Methode ist die Verwendung von NuGet.
- Klicken Sie in Visual Studio mit der rechten Maustaste auf "Abhängigkeiten" und wählen Sie "NuGet-Pakete verwalten ...".
- Wählen Sie die Registerkarte "Durchsuchen" und suchen Sie nach "BarCode.Android".
- Wählen Sie das Paket "BarCode.Android" und klicken auf "Installieren".
Um Probleme mit anderen Plattformen zu vermeiden, ändern Sie die csproj-Datei, um das Paket nur dann einzubeziehen, wenn es auf der Android-Plattform ausgeführt wird. Um dies zu tun:
- Klicken Sie mit der rechten Maustaste auf die *.csproj-Datei Ihres Projekts und wählen Sie "Projektdatei bearbeiten".
- Erstellen Sie ein neues ItemGroup-Element wie folgt:
<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>
- Verschieben Sie den "BarCode.Android" PackageReference in die neu erstellte ItemGroup.
Die obigen Schritte verhindern, dass das "BarCode.Android" Paket auf Plattformen wie iOS verwendet wird. Zu diesem Zweck installieren Sie stattdessen BarCode.iOS.
Konfigurieren Sie das Android-Bundle
Damit Android funktioniert, müssen Sie die Einstellungen des Android-Bundles konfigurieren. Fügen Sie Ihrer ".csproj"-Datei den folgenden Eintrag hinzu, um die Konfigurationsdatei für das Android-Bundle anzugeben:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Erstellen Sie eine Datei namens "BundleConfig.json" im Stammverzeichnis des Projekts. Diese JSON-Datei enthält die erforderlichen Einstellungen für das Android-Bundle, die für die Funktionalität der Bibliothek entscheidend sind.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Diese Konfiguration stellt sicher, dass native Bibliotheken unkomprimiert sind, was ein notwendiger Schritt dafür ist, dass die Bibliothek in der Android-Umgebung ordnungsgemäß funktioniert.
Gestaltung der App-Oberfläche
Aktualisieren Sie die XAML-Datei, um Benutzern die Eingabe von Werten zum Erstellen von Barcodes und QR-Codes zu ermöglichen. Zusätzlich fügen Sie einen Knopf hinzu, um ein Dokument zur Barcode-Erkennung auszuwählen. Hier ist ein Beispiel:
<?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>
Lesen und Schreiben von Barcodes
Aus dem oben gezeigten MainPage.xaml-Code sehen wir, dass das Kontrollkästchen bestimmt, ob der erzeugte Barcode und QR-Code im PDF-Format sein soll. Als Nächstes setzen wir den Lizenzschlüssel. Bitte verwenden Sie einen Test- oder bezahlten Lizenzschlüssel für diesen Schritt.
Der Code prüft und liest den Wert der Variable barcodeInput aus und verwendet dann die Methode CreateBarcode, um den Barcode zu generieren. Schließlich ruft es die Methode SaveToDownloadsAsync auf, die die Datei sowohl für Android als auch für iOS entsprechend speichert.
Auf iOS ist ein benutzerdefinierter Dateipfad erforderlich, um das Dokument in die Anwendung Files zu exportieren.
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
Das Projekt ausführen
Dies zeigt Ihnen, wie Sie das Projekt ausführen und die Barcode-Funktion nutzen können.
Laden Sie das .NET MAUI App-Projekt herunter
Sie können den vollständigen Code für diesen Leitfaden herunterladen. Er kommt als gezippte Datei, die Sie in Visual Studio als .NET MAUI App-Projekt öffnen können.
Häufig gestellte Fragen
Wie kann ich in einer .NET MAUI App für Android Barcodes erstellen und scannen?
Sie können das BarCode.Android-Paket in einem .NET MAUI-Projekt verwenden, um Barcodes auf Android-Geräten zu erstellen und zu scannen. Dies umfasst das Einrichten des Pakets über NuGet in Visual Studio und das Implementieren von Barcode-Funktionalitäten mithilfe bereitgestellter Methoden wie WriteBarcode und ReadBarcode.
Welche Schritte sind notwendig, um die Barcode-Funktionalität für Android in einem .NET MAUI-Projekt einzurichten?
Um die Barcode-Funktionalität in einem .NET MAUI-Projekt einzurichten, installieren Sie das BarCode.Android-Paket über NuGet, konfigurieren Sie Ihre .csproj-Datei, um das Paket bedingt für Android einzuschließen, und stellen Sie sicher, dass Ihr Android-Bundle über eine BundleConfig.json-Datei konfiguriert ist.
Wie konfiguriere ich die .csproj-Datei, um die Barcode-Funktionalität nur für Android einzuschließen?
Bearbeiten Sie die .csproj-Datei, indem Sie eine
Welchen Zweck hat die Verwendung einer BundleConfig.json-Datei in Android-Projekten?
Die BundleConfig.json-Datei wird verwendet, um die Android-Bundle-Einstellungen zu konfigurieren und sicherzustellen, dass native Bibliotheken nicht komprimiert werden. Dies ist für die Funktion des Barcode-Bibliothek auf Android-Geräten von entscheidender Bedeutung.
Wie kann ich eine Benutzeroberfläche für Barcode-Operationen in einer .NET MAUI App gestalten?
Gestalten Sie die App-Oberfläche mit XAML, damit Benutzer Daten eingeben können, um Barcodes und QR-Codes zu erzeugen. Fügen Sie Schaltflächen hinzu, um Dokumente zum Lesen von Barcodes auszuwählen und um Barcodes zu erzeugen, zu speichern und zu scannen.
Welche Methoden werden in C# verwendet, um Barcodes in einer App zu erzeugen und zu lesen?
In einer .NET MAUI App verwenden Sie Methoden wie WriteBarcode, WriteQRcode und ReadBarcode, um Barcodes zu erzeugen, QR-Codes zu erstellen und Barcodes aus Dateien zu lesen.
Wie kann ich die Barcode-Funktionen in meiner .NET MAUI App testen?
Nachdem Sie Ihr Projekt mit den erforderlichen Konfigurationen und Barcode-Code-Implementierungen eingerichtet haben, können Sie die Funktionen testen, indem Sie das Projekt auf einem Android-Gerät oder Emulator über Visual Studio ausführen.
Wo finde ich ein vollständiges .NET MAUI App-Projekt mit Barcode-Funktionalitäten?
Ein vollständiges .NET MAUI App-Projekt mit Barcode-Funktionalitäten kann im ZIP-Format von der IronBarcode-Website heruntergeladen werden. Dieses Projekt kann in Visual Studio zur weiteren Erkundung und Anpassung geöffnet werden.
Ist eine Lizenz erforderlich, um die Barcode-Bibliothek in meinem Android-Projekt zu verwenden?
Ja, die Verwendung der Barcode-Bibliothek in Ihrem Projekt erfordert einen Probe- oder kostenpflichtigen Lizenzschlüssel. Sie müssen diesen Schlüssel im MainPage-Konstruktor eingeben, um die Funktionen der Bibliothek zu aktivieren.

