如何在 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(多平台應用程式 UI)是 Xamarin.Forms 的繼任者,它使開發人員能夠使用 .NET 為 Android、iOS、macOS 和 Windows 建立跨平台應用程式。 它簡化了開發流程,允許創建可在多個平台上無縫運行的原生用戶介面。

BarCode.Android軟體包為 Android 帶來了條碼支援!

IronBarcode Android 套件

BarCode.Android套件透過 .NET 跨平台專案在 Android 裝置上啟用條碼功能。 不需要預設的條碼軟體包。

安裝 BarCode.Android 套件
C# NuGet PDF 庫

使用 NuGet 安裝

安裝 BarCode.Android 套件

建立一個 .NET MAUI 項目

開啟 Visual Studio,然後按一下"建立新專案"。 搜尋 MAUI,選擇 .NET MAUI 應用程序,然後按一下"下一步"。

包含 BarCode.Android 庫

可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。

  1. 在 Visual Studio 中,右鍵按一下"依賴項",然後選擇"管理 NuGet 套件..."。
  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 Bundle

要讓 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 系統上啟用條碼功能?

編輯 .csproj 文件,新增以下內容:並指定目標平台為 Android。將 BarCode.Android 套件包含在此群組中,以確保條碼功能僅為 Android 版本新增。

在 Android 專案中使用 BundleConfig.json 檔案的目的為何?

BundleConfig.json 檔案用於配置 Android 軟體包設置,確保原生庫未被壓縮。這對於條碼庫在 Android 裝置上正常運作至關重要。

如何在.NET MAUI應用程式中設計條碼操作介面?

使用 XAML 設計應用程式介面,使用戶能夠輸入資料以產生條碼和二維碼。介面應包含用於選擇要從中讀取條碼的文件以及產生、儲存和掃描條碼的按鈕。

在 C# 中,應用程式中使用哪些方法來產生和讀取條碼?

在 .NET MAUI 應用程式中,可以使用WriteBarcodeWriteQRcodeReadBarcode等方法分別產生條碼、建立二維碼和從檔案中讀取條碼。

如何在我的 .NET MAUI 應用程式中測試條碼功能?

在完成專案所需的設定和條碼實現後,您可以透過 Visual Studio 在 Android 裝置或模擬器上執行專案來測試各項功能。

在哪裡可以找到一個完整的、具有條碼功能的.NET MAUI應用程式專案?

您可以從 IronBarcode 網站下載包含條碼功能的完整 .NET MAUI 應用程式專案(壓縮套件格式)。此專案可在 Visual Studio 中開啟,以便進行更深入的探索和自訂。

我的 Android 專案使用條碼庫需要許可證嗎?

是的,在您的專案中使用條碼庫需要試用版或付費版許可證金鑰。您需要在 MainPage 建構函數中輸入此金鑰以啟動庫的功能。

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。

準備好開始了嗎?
Nuget 下載 2,035,202 | 版本: 2025.12 剛剛發布