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

This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to 如何在 Android 上使用 .NET MAUI 读取和写入条形码

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

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

IronBarcode Android包

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

安装 BarCode.Android 包
C# 用于 PDF 的 NuGet 库

通过 NuGet 安装

安装 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>
<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>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
XML

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

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

此配置确保本机库被解压缩,这对于库在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 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);
            }
        }
    }
}
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);
            }
        }
    }
}
$vbLabelText   $csharpLabel

运行项目

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

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构造函数中输入此密钥以激活库的功能。

Curtis Chau
技术作家

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

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 2,035,202 | 版本: 2025.12 刚刚发布