IRONSOFTWAREHOME

如何在 Android 上使用 .NET MAUI 读取和写入条形码

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

.NET MAUI(多平台应用程序用户界面)是Xamarin.Forms的继任者,使开发人员能够使用.NET构建用于Android、iOS、macOS和Windows的跨平台应用程序。 它通过允许创建可在多个平台上无缝工作的本机用户界面来简化开发过程。

BarCode.Android包为Android带来了条形码支持!

IronBarcode Android包

BarCode.Android包通过.NET跨平台项目在Android设备上启用条形码功能。 不需要原始BarCode包。

PM > Install-Package BarCode.Android

C# 用于 PDF 的 NuGet 库

通过 NuGet 安装

Install-Package BarCode.Android

创建一个.NET MAUI项目

打开Visual Studio并点击"创建一个新项目"。 搜索MAUI,选择.NET MAUI App,然后点击"下一步"。

包含BarCode.Android库

这个库可以通过多种方式添加。 最简单的方法可能是使用NuGet。

  1. 在Visual Studio中,右键点击"Dependencies"并选择"管理NuGet Packages ..."。
  2. 选择"浏览"选项卡并搜索"BarCode.Android"。
  3. 选择"BarCode.Android"包并点击"安装"。

为了防止在其他平台上出现问题,修改csproj文件以仅在针对Android平台时包含该包。 为此:

  1. 右键点击项目的*.csproj文件,选择"编辑项目文件"。
  2. 创建一个新的ItemGroup元素,如下所示:
<ItemGroup Condition="$(TargetFramework.Contains('android')) == true">
    <PackageReference Include="BarCode.Android" Version="2025.3.4" />
</ItemGroup>
XML
  1. 将"BarCode.Android"PackageReference移动到我们刚创建的ItemGroup中。

以上步骤将防止"BarCode.Android"包在iOS等平台上使用。 为此,请安装BarCode.iOS

配置Android包

要使Android工作,您需要配置Android包设置。 在您的".csproj"文件中,添加以下条目以指定Android包的配置文件:

<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

在项目的根目录下创建一个名为"BundleConfig.json"的文件。 此JSON文件包含Android包所需的设置,这些设置对库的功能至关重要。

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

此配置确保本机库被解压缩,这对于库在Android环境中正常工作是必要的步骤。

设计应用接口

更新XAML文件,以允许用户输入值以生成条形码和二维码。 此外,添加一个按钮以选择用于条形码读取的文档。 以下是一个例子:

<?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

读取和写入条形码

从上面的MainPage.xaml代码中,我们可以看到复选框决定生成的条形码和二维码是否应该是PDF格式。 接下来,我们设置许可证密钥。 请使用试用或付费许可证密钥进行此步骤。

代码检查并从barcodeInput变量中检索值,然后使用CreateBarcode方法生成条形码。 最后,调用SaveToDownloadsAsync方法,在Android和iOS上适当地保存文件。

在iOS上,需要自定义文件路径才能将文档导出到Files应用程序。

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);
            }
        }
    }
}

运行项目

这将向您展示如何运行项目并使用条形码功能。

Execute .NET MAUI App project

下载.NET MAUI应用程序项目

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

点击此处下载项目。

常见问题解答

如何在Android的.NET MAUI应用程序中创建和扫描条形码?

您可以在.NET MAUI项目中使用BarCode.Android包来在Android设备上创建和扫描条形码。这涉及通过Visual Studio中的NuGet设置包,并使用提供的方法如WriteBarcodeReadBarcode实现条形码功能。

在.NET MAUI项目中设置Android条形码功能需要哪些步骤?

要在.NET MAUI项目中设置条形码功能,请使用NuGet安装BarCode.Android包,配置.csproj文件以有条件地为Android包含此包,并通过BundleConfig.json文件确保配置Android包。

如何配置.csproj文件以仅为Android包含条形码功能?

通过添加一个条件以定位Android来编辑.csproj文件。在此组中包含BarCode.Android包以确保条形码功能只为Android版本添加。

在Android项目中使用BundleConfig.json文件的目的是什么?

BundleConfig.json文件用于配置Android的包设置,确保原生库未压缩。这对于条形码库在Android设备上正常工作至关重要。

如何在.NET MAUI应用程序中设计条形码操作界面?

使用XAML设计应用程序界面,允许用户输入数据以生成条形码和二维码。包括用于选择文档以读取条形码和生成、保存、扫描条形码的按钮。

在应用程序中使用C#生成和读取条形码的方法是什么?

在.NET MAUI应用程序中,使用方法如WriteBarcodeWriteQRcodeReadBarcode来生成条形码、创建二维码和读取文件中的条形码。

如何在.NET MAUI应用程序中测试条形码功能?

在对项目进行必要的配置和条形码代码实现后,您可以通过Visual Studio在Android设备或模拟器上运行项目来测试功能。

在哪里可以找到带有条形码功能的完整.NET MAUI应用程序项目?

完整的带有条形码功能的.NET MAUI应用程序项目可以从IronBarcode网站下载为压缩格式。该项目可以在Visual Studio中打开以进行进一步探索和定制。

在我的Android项目中使用条形码库是否需要许可证?

是的,在项目中使用条形码库需要试用或付费许可证密钥。您需要在MainPage构造函数中输入此密钥以激活库的功能。

What functionalities does IronBarcode provide for reading barcode data from files?

IronBarcode can read barcodes from image and PDF files using the BarcodeReader class, with results formatted and displayed accordingly in the application.

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

准备开始了吗?

Nuget Downloads 2,422,100版本:2026.9刚刚发布

立即获取您的免费30 天试用密钥
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索 "IronBarcode"
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

  1. 下载并将 IronBarCode 解压到解决方案目录中的 ~/Libs 等位置
  2. 在 Visual Studio 解决方案资源管理器中,右键单击引用。选择浏览,"IronBarcode.dll"

许可 $999

Key in blue circle

立即获取免费的 30 天试用版密钥

Your trial license will be sent to your email address

无任何限制。100% 解锁。无需信用卡。

bullet_checked无需信用卡或创建账户无任何限制。100% 解锁。无需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
预约您的免费现场演示
Booking Badge

深受全球数百万工程师信赖

Iron Software 的客户徽标
获取您的无义务咨询
填写下面的表格或通过sales@ironsoftware.com
您的资料将始终保密。
深受全球数百万工程师信赖
Iron Software 的客户徽标
立即获取您的免费30 天试用密钥
无需信用卡或创建账户