如何在 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 裝置上啟用條碼功能。 不需要預設的條碼軟體包。

Install-Package
用於 PDF 的 C# NuGet庫
### 使用NuGet安裝
Install-Package

建立一個.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 實現條形碼功能。

設置 Android 的 .NET MAUI 項目中條形碼功能需要哪些步驟?

要在 .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 App 項目?

可以從 IronBarcode 網站以壓縮格式下載完整的 .NET MAUI App 項目。該項目可以在 Visual Studio 中打開以進一步探索和定制。

在我的 Android 項目中使用條形碼庫需要許可證嗎?

是的,在您的項目中使用條形碼庫需要試用或付費許可證密鑰。您需要在 MainPage 構造函數中輸入此密鑰以激活庫的功能。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。

準備好開始了嗎?
Nuget 下載 2,108,094 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。