.NET MAUI で Android のバーコードを読み書きする方法
.NET MAUI (Multi-platform App UI)はXamarin.Formsの後継であり、開発者が.NETを使用してAndroid、iOS、macOS、Windows用のクロスプラットフォームアプリケーションを構築できるようにします。 これは、複数のプラットフォームでシームレスに動作するネイティブユーザーインターフェイスの作成を可能にすることにより、開発プロセスを合理化します。
BarCode.Androidパッケージは、Androidにバーコードサポートをもたらします!
.NET MAUI で Android のバーコードを読み書きする方法
IronBarcode Android パッケージ
BarCode.Androidパッケージは、.NETクロスプラットフォームプロジェクトを通じてAndroidデバイスにバーコード機能を提供します。 バニラのBarCodeパッケージは必要ありません。
インストールパッケージ BarCode.Android
Install with NuGet
インストールパッケージ BarCode.Android
.NET MAUIプロジェクトの作成
Visual Studioを開き、"新しいプロジェクトを作成"をクリックします。 MAUIを検索し、.NET MAUIアプリを選択して"次へ"をクリックします。
BarCode.Androidライブラリを含める
ライブラリを追加する方法はいくつかあります。 最も簡単なのは、おそらくNuGetを使用することです。
- Visual Studio内で"Dependencies"を右クリックし、"Manage NuGet Packages ..."を選択します。
- "Browse"タブを選択して"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>- "BarCode.Android"のPackageReferenceを作成したItemGroup内に移動します。
上記の手順により、iOSなどのプラットフォームでは"BarCode.Android"パッケージが使用されることはありません。 その目的のために、BarCode.iOSを代わりにインストールしてください。
Androidバンドルを構成する
Androidが動作するには、Androidバンドルの設定を構成する必要があります。 ".csproj"ファイル内に、Androidバンドルの設定ファイルを指定するための次のエントリを追加してください:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile><AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>プロジェクトのルートディレクトリに"BundleConfig.json"という名前のファイルを作成します。 このJSONファイルには、Androidバンドルに必要な設定が含まれており、ライブラリの機能にとって重要です。
{
"optimizations": {
"uncompress_native_libraries": {}
}
}この設定により、ネイティブライブラリが圧縮されず、Android環境でライブラリが正常に動作するために必要なステップとなります。
アプリインターフェースを設計する
XAMLファイルを更新して、ユーザーがバーコードおよびQRコードを生成するための値を入力できるようにします。 さらに、バーコード読み取り用のドキュメントを選択するボタンを追加します。 こちらが例です:
<?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>バーコードを読み書きする
上記のMainPage.xamlコードから、チェックボックスが生成されたバーコードおよびQRコードが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プロジェクトを実行する
これにより、プロジェクトを実行してバーコード機能を使用する方法が示されます。

.NET MAUIアプリプロジェクトをダウンロードする
このガイドの完全なコードをダウンロードできます。これは.zipファイルとして提供され、Visual Studioで.NET MAUIアプリプロジェクトとして開くことができます。
よくある質問
.NET MAUIアプリでAndroid向けにバーコードを作成しスキャンするにはどうすればよいですか?
.NET MAUIプロジェクト内でBarCode.Androidパッケージを使用してAndroidデバイス上でバーコードを作成しスキャンすることができます。これには、Visual Studioを通じてNuGetでパッケージを設定し、提供されたWriteBarcodeやReadBarcodeなどのメソッドを使用したバーコード機能の実装が含まれます。
Android用に.NET MAUIプロジェクトでバーコード機能を設定するために必要な手順は何ですか?
.NET MAUIプロジェクトでのバーコード機能の設定には、NuGetを使用してBarCode.Androidパッケージをインストールし、csprojファイルを編集してAndroidに対して条件付きでパッケージを含めるように構成し、BundleConfig.jsonファイルを通じてAndroidバンドルを設定することが含まれます。
バーコード機能をAndroidのみで含めるためにcsprojファイルをどのように設定しますか?
.csprojファイルを編集して、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アプリプロジェクトはどこで見つけられますか?
バーコード機能を備えた完全な.NET MAUIアプリプロジェクトは、IronBarcodeのウェブサイトからジップ形式でダウンロードできます。このプロジェクトはVisual Studioで開いてさらに探求したりカスタマイズすることができます。
Androidプロジェクトでバーコードライブラリを使用するにはライセンスが必要ですか?
はい、プロジェクトでバーコードライブラリを使用するには、トライアルまたは有料のライセンスキーが必要です。このキーをMainPageコンストラクターに入力して、ライブラリの機能をアクティブにする必要があります。






