.NET MAUI'de Android Üzerine Barkod Nasıl Okunur ve Yazılır
.NET MAUI (Çok platformlu Uygulama UI'si), Xamarin.Forms'un halefidir, geliştiricilerin Android, iOS, macOS ve Windows için çapraz platform uygulamaları oluşturmalarını sağlar. Çoklu platformlarda kusursuz bir şekilde çalışan yerel kullanıcı arayüzleri oluşturmaya olanak sağlayarak geliştirme sürecini geliştirir.
BarCode.Android paketi, Android için barkod desteği getirir!
.NET MAUI'de Android Üzerine Barkod Nasıl Okunur ve Yazılır
IronBarcode Android Paketi
BarCode.Android paketi, .NET çapraz platform projeleri aracılığıyla Android cihazlarda barkod özelliklerini etkinleştirir. Vanilya BarCode paketi gerekli değildir.
Install-Package BarCode.Android
NuGet ile yükleyin
Install-Package BarCode.Android
.NET MAUI Projesi Oluşturun
Visual Studio'yu açın ve "Yeni bir proje oluştur"u tıklayın. MAUI'yi arayın, .NET MAUI Uygulamasını seçin ve "Next"e tıklayın.
BarCode.Android Kütüphanesini Dahil Edin
Kütüphane çeşitli şekillerde eklenebilir. Belki en kolay yolu NuGet kullanmaktır.
- Visual Studio içinde "Bağımlılıklar" üzerine sağ tıklayın ve "NuGet Paketlerini Yönet ..."i seçin.
- "Gözat" sekmesini seçin ve "BarCode.Android"i arayın.
- "BarCode.Android" paketini seçin ve "Install" tuşuna basın.
Diğer platformlarla ilgili sorunları önlemek için csproj dosyasını düzenleyin ve paketi yalnızca Android platformunu hedeflerken dahil edin. Bunu yapmak için:
- Projeniz için *.csproj dosyasına sağ tıklayın ve "Proje Dosyasını Düzenle"yi seçin.
- Aşağıdaki gibi yeni bir ItemGroup öğesi oluşturun:
<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>
- Az önce oluşturduğumuz ItemGroup içine "BarCode.Android" PackageReference'ını taşıyın.
Yukarıdaki adımlar, "BarCode.Android" paketinin iOS gibi platformlarda kullanılmasını engelleyecektir. Bu amaç için, bunun yerine BarCode.iOS'u yükleyin.
Android Paketini Yapılandırın
Android'in çalışması için, Android paket ayarlarını yapılandırmanız gerekiyor. ".csproj" dosyanıza, Android paketi için yapılandırma dosyasını belirtmek üzere aşağıdaki girişi ekleyin:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Projenin kök dizininde "BundleConfig.json" adlı bir dosya oluşturun. Bu JSON dosyası, Android paketinin işlevselliği için gerekli olan ayarları içerir.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Bu yapılandırma, yerel kütüphanelerin sıkıştırılmamış olmasını sağlar, bu da kütüphanenin Android ortamında düzgün çalışması için gerekli bir adımdır.
Uygulama Arayüzünü Tasarlayın
XAML dosyasını güncelleyerek kullanıcıların barkodlar ve QR kodları oluşturmak için değerler girmesine izin verin. Ek olarak, barkod okumak için belge seçimi yapmak amacıyla bir buton ekleyin. İşte bir örnek:
<?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>
Barkodları Oku ve Yaz
Yukarıdaki MainPage.xaml kodundan, oluşturulan barkod ve QR kodunun PDF formatında olup olmayacağını belirleyebilmek için onay kutusu kullanıldığını görebiliriz. Sonraki adımda lisans anahtarını ayarlıyoruz. Bu adım için lütfen bir deneme veya ücretli lisans anahtarı kullanın.
Kod, barcodeInput değişkeninden değeri kontrol eder ve alır, ardından barkodu üretmek için CreateBarcode yöntemini kullanır. Son olarak, Android ve iOS için dosyayı uygun şekilde kaydeden SaveToDownloadsAsync yöntemini çağırır.
iOS'ta, belgeyi Files uygulamasına aktarmak için özel bir dosya yolu gereklidir.
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
Projeyi Çalıştır
Bu, size projeyi nasıl çalıştıracağınızı ve barkod özelliğini nasıl kullanacağınızı gösterecektir.
.NET MAUI Uygulama Projesini İndirin
Bu rehber için tamamlanmış kodu indirebilirsiniz. Açık bir Visual Studio'da bir .NET MAUI Uygulama projesi olarak açabileceğiniz sıkıştırılmış bir dosya ile birlikte gelir.
Sıkça Sorulan Sorular
Android için bir .NET MAUI uygulamasında barkodları nasıl oluşturabilir ve tarayabilirim?
.NET MAUI projesinde Android cihazlarda barkod oluşturmak ve taramak için BarCode.Android paketini kullanabilirsiniz. Bu, Visual Studio'da NuGet aracılığıyla paketi kurmayı ve WriteBarcode ve ReadBarcode gibi sağlanan yöntemleri kullanarak barkod işlevlerini uygulamayı içerir.
Bir .NET MAUI projesinde Android için barkod işlevselliği kurmak için hangi adımlar gereklidir?
.NET MAUI projesinde barkod işlevselliğini kurmak için, NuGet kullanarak BarCode.Android paketini yükleyin, .csproj dosyanızı Android için paketi şartlı olarak dahil edecek şekilde yapılandırın ve Android paketinizin bir BundleConfig.json dosyası aracılığıyla yapılandırıldığından emin olun.
.csproj dosyasını sadece Android için barkod işlevselliği eklemek amacıyla nasıl yapılandırırım?
.csproj dosyasına Android'e yönelik bir koşulla beraber bir
Android projelerinde BundleConfig.json dosyasının amacı nedir?
BundleConfig.json dosyası Android paket ayarlarını yapılandırmak için kullanılır ve yerel kütüphanelerin sıkıştırılmadığından emin olur. Bu, barkod kütüphanesinin Android cihazlarda doğru çalışabilmesi için esastır.
.NET MAUI uygulamasında barkod işlemleri için bir arayüz nasıl tasarlayabilirim?
Kullanıcıların barkod ve QR kodları oluşturmak için veri girebilmelerini sağlamak amacıyla XAML kullanarak uygulama arayüzünü tasarlayın. Barkod okumak için belgeleri seçmek ve barkod oluşturma, kaydetme ve tarama için butonlar ekleyin.
Bir uygulamada barkod oluşturmak ve okumak için C#'ta hangi yöntemler kullanılır?
.NET MAUI uygulamasında barkod oluşturmak, QR kod oluşturmak ve dosyalardan barkodları okumak için WriteBarcode, WriteQRcode ve ReadBarcode gibi yöntemler kullanılabilir.
.NET MAUI uygulamamda barkod özelliklerini nasıl test edebilirim?
Projenizi gerekli yapılandırmalar ve barkod kod uygulamaları ile kurduktan sonra, Visual Studio aracılığıyla projeyi bir Android cihazda veya emülatörde çalıştırarak özellikleri test edebilirsiniz.
Barkod işlevleri içeren eksiksiz bir .NET MAUI uygulama projesini nerede bulabilirim?
Barkod işlevleri içeren eksiksiz bir .NET MAUI uygulama projesi, IronBarcode web sitesinden sıkıştırılmış formatta indirilebilir. Bu proje Visual Studio'da daha fazla keşif ve özelleştirme için açılabilir.
Android projemde barkod kütüphanesini kullanmak için lisans gerekli midir?
Evet, projenizde barkod kütüphanesini kullanmak için bir deneme veya ücretli lisans anahtarı gereklidir. Bu anahtarı, kütüphanenin özelliklerini etkinleştirmek için MainPage kurucusuna girmelisiniz.

