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

This article was translated from English: Does it need improvement?
Translated
View the article in English
Android related to 如何在.NET MAUI中讀寫Android上的條碼

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

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

IronBarcode Android套件

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

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>
<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檔案以允許使用者輸入值以生成條碼和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 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);
            }
        }
    }
}
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);
            }
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronBarCode
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Xamarin.Essentials

Namespace IronBarcodeMauiAndroid
	Partial Public Class MainPage
		Inherits ContentPage

		Public Property IsGeneratePdfChecked() As Boolean
			Get
				Return generatePdfCheckBox.IsChecked
			End Get
			Set(ByVal value As Boolean)
				generatePdfCheckBox.IsChecked = value
			End Set
		End Property

		Public Sub New()
			InitializeComponent()
			' Set the license key for IronBarcode, replace with your actual license key.
			License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
		End Sub

		Private Async Sub WriteBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(barcodeInput.Text) Then
					' Create a barcode from the text input with the EAN13 encoding.
					Dim barcode = BarcodeWriter.CreateBarcode(barcodeInput.Text, BarcodeEncoding.EAN13)

					' Determine the file extension and data format based on the checkbox state.
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"Barcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(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")
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Private Async Sub WriteQRcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				If Not String.IsNullOrEmpty(qrInput.Text) Then
					' Create a QR code from the text input.
					Dim barcode = QRCodeWriter.CreateQrCode(qrInput.Text)

					' Determine the file extension and data format based on the checkbox state.
					Dim fileExtension As String = If(IsGeneratePdfChecked, "pdf", "png")
					Dim fileName As String = $"QRcode_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}"
					Dim fileData() As Byte = If(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")
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Private Async Sub ReadBarcode(ByVal sender As Object, ByVal e As EventArgs)
			Try
				Dim options = New PickOptions With {.PickerTitle = "Please select a file"}
				Dim file = Await FilePicker.PickAsync(options)

				OutputText.Text = ""

				If file IsNot Nothing Then
					Dim stream = Await file.OpenReadAsync()

					Dim result As BarcodeResults

					If file.ContentType.Contains("image") Then
						' Read barcodes from an image file.
						result = BarcodeReader.Read(stream)
					Else
						' Read barcodes from a PDF file.
						result = BarcodeReader.ReadPdf(stream)
					End If

					Dim barcodeResult As String = ""
					Dim count As Integer = 1

					' Retrieve and format the barcode reading results.
					result.ForEach(Sub(x)
						barcodeResult &= $"Barcode {count}: {x.Value}" & vbLf
						count += 1
					End Sub)

					OutputText.Text = barcodeResult
				End If
			Catch ex As Exception
				' Handle exceptions and log the error.
				System.Diagnostics.Debug.WriteLine(ex)
			End Try
		End Sub

		Public Async Function SaveToDownloadsAsync(ByVal fileData() As Byte, ByVal fileName As String) As Task
			Dim downloadsPath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads)
			Dim filePath = Path.Combine(downloadsPath.AbsolutePath, fileName)

			Try
				' Create the directory if it doesn't exist.
				If Not Directory.Exists(downloadsPath.AbsolutePath) Then
					Directory.CreateDirectory(downloadsPath.AbsolutePath)
				End If

				' Save the file to the Downloads folder.
				Await File.WriteAllBytesAsync(filePath, fileData)
			Catch ex As Exception
				' Log errors if file saving fails.
				System.Diagnostics.Debug.WriteLine("Error saving file: " & ex.Message)
			End Try
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

運行專案

這將向您展示如何運行專案並使用條碼功能。

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構造函式中輸入此金鑰以激活程式庫的功能。

IronBarcode支援條碼的批量處理嗎?

是的,IronBarcode支援批量處理,允許開發人員在一次操作中生成或讀取多個條碼,提高大規模應用的效率。

Curtis Chau
技術作家

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

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 2,317,217 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動嗎?

想快速驗證嗎? PM > Install-Package BarCode
運行範例觀看您的字串成為條碼。