IRONSOFTWAREHOME

如何在.NET MAUI中讀寫Android上的條碼

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

.NET MAUI (多平台應用程式UI) 是Xamarin.Forms的繼任者,使開發者能夠使用.NET建立適用於Android、iOS、macOS和Windows的跨平台應用程式。 它通過允許建立跨多個平台順利運作的原生使用者介面來簡化開發過程。

BarCode.Android 套件為Android提供條碼支援!

IronBarcode Android套件

BarCode.Android 套件通過 .NET 跨平台專案使 Android 裝置具備條碼功能。 不需要vanilla BarCode套件。

PM > Install-Package BarCode.Android

C# NuGet程式庫適用於PDF

使用 NuGet 安裝

Install-Package BarCode.Android

建立一個.NET MAUI專案

打開Visual Studio並點擊"建立新專案"。 搜尋MAUI,選擇 .NET MAUI App並點擊"下一步"。

包含BarCode.Android程式庫

此程式庫可以以多種方式新增。 最簡便的方法可能是使用NuGet。

  1. 在Visual Studio中,右鍵單擊"Dependencies"並選擇"管理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>
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檔案以允許使用者輸入值以生成條碼和QR Code。 此外,新增一個按鈕以選擇文件進行條碼閱讀。 以下為範例:

<?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程式碼中,我們可以看到勾選框決定生成的條碼和QR Code是否應為PDF格式。 接下來,我們設置授權金鑰。 此步驟請使用試用或付費授權金鑰。

程式碼檢查並從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 App專案開啟。

按此下載專案。

常見問題

如何在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設計應用介面,以允許使用者輸入資料以生成條碼和QR碼。包含按鈕以選擇要從中讀取條碼的文件以及生成、保存和掃描條碼。

在應用中使用哪些C#方法來生成和讀取條碼?

在.NET MAUI應用中,使用WriteBarcodeWriteQRcodeReadBarcode等方法來生成條碼、建立QR碼並從檔案中讀取條碼。

如何測試我在.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擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備好開始了嗎?

Nuget Downloads 2,422,100版本:2026.9剛剛發布

立即獲取您的免費30天試用金鑰
不需要信用卡或帳戶建立
C# NuGet程式庫,用於PDF
通過NuGet安裝

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解決方案資源管理器中,右鍵點擊References,管理NuGet包
  2. 選擇瀏覽並搜尋"IronBarCode"
  3. 選擇包並安裝
C# PDF DLL
下載DLL

版本: 2026.9

  1. 下載並解壓IronBarCode至您的Solution目錄中的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中右鍵點擊References,選擇瀏覽,"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天試用金鑰
無需信用卡或帳戶建立