IronBarcode 開始使用 在 Android 上設置 如何在 Android 上使用 .NET MAUI 讀取和寫入條碼 Curtis Chau 更新:2025年6月29日 下載 IronBarcode NuGet 下載 DLL 下載 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 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 函式庫下載指令標籤 ::開始 --> ### 使用 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 應用中創建和掃描條形碼? 您可以在 .NET MAUI 項目中使用 BarCode.Android 包在 Android 設備上創建和掃描條形碼。這涉及到在 Visual Studio 中通過 NuGet 設置包,以及使用提供的方法如 WriteBarcode 和 ReadBarcode 實現條形碼功能。 設置 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 應用中,使用 WriteBarcode、WriteQRcode 和 ReadBarcode 等方法分別生成條形碼、創建 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 bots,將他對技術的熱愛與創意結合。 準備好開始了嗎? Nuget 下載 2,070,733 | 版本: 2026.2 剛剛發布 免費 NuGet 下載 總下載量:2,070,733 查看許可證