如何在.NET MAUI的Android平台上读取和写入条形码
.NET MAUI(多平台应用 UI)是 Xamarin.Forms 的继任者,使开发者能够使用 .NET 构建适用于 Android、iOS、macOS 和 Windows 的跨平台应用程序。 它通过允许创建在多个平台上无缝运行的本地用户界面来简化开发过程。
BarCode.Android 包为 Android 带来了条形码支持!!
如何在.NET MAUI的Android平台上读取和写入条形码
IronBarcode Android 套件
BarCode.Android 包通过 .NET 跨平台项目在 Android 设备上启用条形码功能。 不需要原始的BarCode包。
PM > Install-Package BarCode.Android
使用 NuGet 安装
Install-Package BarCode.Android
创建一个.NET MAUI项目
打开 Visual Studio 并点击“创建新项目”。 搜索 MAUI,选择 .NET MAUI 应用程序然后点击“下一步”。
包含BarCode.Android库
可以通过多种方式添加库。 或许使用 NuGet 是最简单的方式。
在 Visual Studio 中,右键单击“依赖项”并选择“管理 NuGet 包...”。
选择“浏览”选项卡,并搜索“BarCode.Android”。
选择 "BarCode.Android" 包,然后点击 "Install"。
为了防止与其他平台发生问题,请修改 csproj 文件,使其仅在针对 Android 平台时包含该软件包。 为了做到这一点:
右键单击项目的 *.csproj 文件,然后选择“编辑项目文件”。
- 创建一个新的 ItemGroup 元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
<PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
将 "BarCode.Android" 的 PackageReference 移动到我们刚刚创建的 ItemGroup 内。
上述步骤将防止“BarCode.Android”包在诸如 iOS 等平台上使用。 为此,请改为安装BarCode.iOS。
配置 Android Bundle
要使 Android 正常工作,您需要配置 Android 绑定设置。 在您的“.csproj”文件中,添加以下条目以指定Android捆绑包的配置文件:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
在项目根目录中创建一个名为 "BundleConfig.json" 的文件。 这个JSON文件包含Android包所需的设置,这些设置对库的功能至关重要。
{
"optimizations" :
{
"uncompress_native_libraries" : {}
}
}
此配置确保本机库被解压缩,这是库在 Android 环境中正常运行所需的步骤。
设计应用程序界面
更新XAML文件以允许用户输入值来生成条形码和QR码。 另外,添加一个按钮来选择用于条形码读取的文档。 下面是一个例子:
<?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>
读取和写入条形码
从上述 MainPage.xaml 代码中,我们可以看到复选框决定生成的条形码和二维码是否应为 PDF 格式。 接下来,我们设置许可证密钥。 请在此步骤中使用试用版或付费版许可证密钥。
代码检查并检索barcodeInput变量的值,然后使用CreateBarcode
方法生成条形码。 最后,它调用SaveToDownloadsAsync
方法,该方法能够在Android和iOS上正确保存文件。
在 iOS 上,导出文档到 文件 应用程序需要自定义文件路径。
using IronBarCode;
namespace IronBarcodeMauiAndroid
{
public partial class MainPage : ContentPage
{
public bool IsGeneratePdfChecked
{
get => generatePdfCheckBox.IsChecked;
set
{
generatePdfCheckBox.IsChecked = value;
}
}
public MainPage()
{
InitializeComponent();
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions
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"))
{
result = BarcodeReader.Read(stream);
}
else
{
result = BarcodeReader.ReadPdf(stream);
}
string barcodeResult = "";
int count = 1;
result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
{
#if ANDROID
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)
{
System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
}
#endif
}
}
}
using IronBarCode;
namespace IronBarcodeMauiAndroid
{
public partial class MainPage : ContentPage
{
public bool IsGeneratePdfChecked
{
get => generatePdfCheckBox.IsChecked;
set
{
generatePdfCheckBox.IsChecked = value;
}
}
public MainPage()
{
InitializeComponent();
License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
}
private async void WriteBarcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(barcodeInput.Text))
{
var barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
private async void WriteQRcode(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(qrInput.Text))
{
var barcode = QRCodeWriter.CreateQrCode(qrInput.Text);
// Generate file name
string fileExtension = IsGeneratePdfChecked ? "pdf" : "png";
string fileName = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}";
byte[] fileData = IsGeneratePdfChecked ? barcode.ToPdfBinaryData() : barcode.ToPngBinaryData();
// Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
await SaveToDownloadsAsync(fileData, fileName);
await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK");
}
}
catch (Exception ex)
{
// Handle exceptions
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"))
{
result = BarcodeReader.Read(stream);
}
else
{
result = BarcodeReader.ReadPdf(stream);
}
string barcodeResult = "";
int count = 1;
result.ForEach(x => { barcodeResult += $"barcode {count}: {x.Value}\n"; count++; });
OutputText.Text = barcodeResult;
}
}
catch (Exception ex)
{
// Handle exceptions
System.Diagnostics.Debug.WriteLine(ex);
}
}
public async Task SaveToDownloadsAsync(byte[] fileData, string fileName)
{
#if ANDROID
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)
{
System.Diagnostics.Debug.WriteLine("Error saving file: " + ex.Message);
}
#endif
}
}
}
Imports Microsoft.VisualBasic
Imports IronBarCode
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()
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
Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)
' Generate file name
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())
' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions
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
Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)
' Generate file name
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())
' Get file saver instance and save the file to the Downloads folder (or Documents on iOS)
Await SaveToDownloadsAsync(fileData, fileName)
Await Application.Current.MainPage.DisplayAlert("Saved", "File saved to Downloads folder", "OK")
End If
Catch ex As Exception
' Handle exceptions
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
result = BarcodeReader.Read(stream)
Else
result = BarcodeReader.ReadPdf(stream)
End If
Dim barcodeResult As String = ""
Dim count As Integer = 1
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
System.Diagnostics.Debug.WriteLine(ex)
End Try
End Sub
Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
#If ANDROID Then
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
System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
End Try
#End If
End Function
End Class
End Namespace
运行项目
这将向您展示如何运行项目并使用条形码功能。

下载 .NET MAUI 应用程序项目
您可以下载本指南的完整代码。它以压缩文件的形式提供,您可以将其作为.NET MAUI App项目在Visual Studio中打开。