IronBarcode 開始 在 Android 上設定 如何在 Android 上使用 .NET MAUI 讀取和寫入條碼 Curtis Chau 更新:6月 29, 2025 下載 IronBarcode NuGet 下載 DLL 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在雙子座打開 請向 Gemini 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 This article was translated from English: Does it need improvement? Translated View the article in English .NET MAUI(多平台應用程式 UI)是 Xamarin.Forms 的繼任者,它使開發人員能夠使用 .NET 為 Android、iOS、macOS 和 Windows 建立跨平台應用程式。 它簡化了開發流程,允許創建可在多個平台上無縫運行的原生用戶介面。 BarCode.Android軟體包為 Android 帶來了條碼支援! 如何在 Android 上使用 .NET MAUI 讀取和寫入條碼 下載用於在 Android 上讀寫條碼的 C# 函式庫 Create a .NET MAUI App project Edit the XAML file to add an activation button and display output text Edit the corresponding C# file to handle barcode recognition Download the sample project for a quick start IronBarcode Android 套件 BarCode.Android套件透過 .NET 跨平台專案在 Android 裝置上啟用條碼功能。 不需要預設的條碼軟體包。 安裝 BarCode.Android 套件 使用 NuGet 安裝 安裝 BarCode.Android 套件 nuget.org/packages/BarCode.Android/ 建立一個 .NET MAUI 項目 開啟 Visual Studio,然後按一下"建立新專案"。 搜尋 MAUI,選擇 .NET MAUI 應用程序,然後按一下"下一步"。 包含 BarCode.Android 庫 可以透過多種方式新增庫。 最簡單的方法或許是使用 NuGet。 在 Visual Studio 中,右鍵按一下"依賴項",然後選擇"管理 NuGet 套件..."。 選擇"瀏覽"選項卡,搜尋"BarCode.Android"。 選擇"BarCode.Android"軟體包,然後點選"安裝"。 為防止與其他平台出現問題,請修改 csproj 文件,使其僅在面向 Android 平台時包含該軟體套件。 為了做到這一點: 右鍵點選專案的 *.csproj 文件,然後選擇"編輯專案文件"。 建立一個新的 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 將"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); } } } } 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 運行專案 這將向您展示如何運行項目和使用條碼功能。 下載 .NET MAUI 應用程式項目 您可以下載本指南的完整程式碼。它以壓縮檔案的形式提供,您可以在 Visual Studio 中將其作為 .NET MAUI 應用程式專案開啟。 點擊此處下載項目。 常見問題解答 如何在 Android 的 .NET MAUI 應用程式中建立並掃描 BarCode? 您可以在 .NET MAUI 專案中使用 BarCode.Android 套件在 Android 裝置上建立和掃描條碼。這包括在 Visual Studio 中透過 NuGet 設定套件,並使用所提供的方法實作條碼功能,例如 WriteBarcode 和 ReadBarcode 。 在 .NET MAUI 專案中為 Android 設定 BarCode 功能需要哪些步驟? 要在 .NET MAUI 專案中設定條碼功能,請使用 NuGet 安裝 BarCode.Android 套件,配置您的 .csproj 檔案以有條件地包含 Android 的套件,並確保您的 Android bundle 已透過 BundleConfig.json 檔案進行配置。 如何設定 .csproj 檔案,使其僅包含 Android 的 BarCode 功能? 編輯 .csproj 檔案,加入 與針對 Android 的條件。在此組中包含 BarCode.Android 套件,以確保僅針對 Android 建置新增條碼功能。 在 Android 專案中使用 BundleConfig.json 檔案的目的為何? BundleConfig.json 檔案用於設定 Android 的 bundle 設定,確保原生函式庫未經壓縮。這對於 BarCode 函式庫在 Android 裝置上正常運作是不可或缺的。 如何在 .NET MAUI 應用程式中設計條碼操作介面? 使用 XAML 設計應用程式介面,讓使用者輸入資料以產生 BarCode 和 QR 代碼。包括選擇文件以讀取條碼的按鈕,以及產生、儲存和掃描條碼的按鈕。 C# 中使用哪些方法在應用程式中產生和讀取 BarCode? 在 .NET MAUI 應用程式中,使用 WriteBarcode, WriteQRcode, 和 ReadBarcode 等方法,分別產生條碼、建立 QR 碼,以及從檔案讀取條碼。 如何測試 .NET MAUI 應用程式中的 BarCode 功能? 在使用必要的配置和 BarCode 實作設定專案後,您可以透過 Visual Studio 在 Android 裝置或模擬器上執行專案來測試功能。 我在哪裡可以找到具有條碼功能的完整 .NET MAUI App 專案? 可從 IronBarcode 網站以壓縮格式下載具有條碼功能的完整 .NET MAUI App 專案。此專案可在 Visual Studio 中開啟,以進一步探索和客製化。 在我的 Android 專案中使用 BarCode 函式庫是否需要授權? 是的,在您的專案中使用 BarCode 函式庫需要試用或付費的授權金鑰。您需要在 MainPage 構建程式中輸入此金鑰,以啟用程式庫的功能。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 準備好開始了嗎? Nuget 下載 1,979,979 | Version: 2025.11 剛發表 免費下載 NuGet 下載總數:1,979,979 檢視授權