Android'de .NET MAUI'de Barkod Okuma ve Yazma
.NET MAUI (Çoklu platform Uygulama Arayüzü), Xamarin.Forms'un halefidir ve geliştiricilere Android, iOS, macOS ve Windows için çapraz platform uygulamaları oluşturma imkanı sunar. Farklı platformlarda kesintisiz çalışan yerel kullanıcı arayüzlerinin oluşturulmasını sağlayarak geliştirme sürecini hızlandırır.
BarCode.Android paketi, Android'e BarCode desteği getiriyor!
Android'de .NET MAUI'de Barkod Okuma ve Yazma
IronBarcode Android Paketi
BarCode.Android paketi, .NET çapraz platform projeleri aracılığıyla Android cihazlarda BarCode özelliklerini etkinleştirir. Vanilya BarCode paketi gerekli değildir.
Install-Package BarCode.Android
NuGet ile yükleyin
Install-Package BarCode.Android
Bir .NET MAUI Projesi Oluşturun
Visual Studio'yu açın ve "Yeni proje oluştur"a tıklayın. MAUI arayın, .NET MAUI Uygulamasını seçin ve "İleri" tıklayın.
BarCode.Android Kütüphanesini Ekleyin
Kütüphane çeşitli şekillerde eklenebilir. Belki de en kolay yol NuGet kullanmaktır.
- Visual Studio içinde "Dependencies" üzerine sağ tıklayın ve "NuGet Paketlerini Yönet..." seçeneğini seçin.
- "Gözat" sekmesini seçin ve "BarCode.Android" arayın.
- "BarCode.Android" paketini seçin ve "Yükle"ye tıklayın.
Diğer platformlarla sorun yaşamamak için csproj dosyanızı yalnızca Android platformunu hedefleyerek paketi dahil edecek şekilde değiştirin. Bunu yapmak için:
- Projenizin *.csproj dosyası üzerine sağ tıklayın ve "Proje Dosyasını Düzenle" seçeneğini seçin.
- Yeni bir ItemGroup elementi 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>
- "BarCode.Android" PackageReference öğesini yeni oluşturduğumuz ItemGroup içine taşıyın.
Yukarıdaki adımlar, "BarCode.Android" paketinin iOS gibi platformlarda kullanılmasını önleyecektir. Bu amaçla bunun yerine BarCode.iOS yükleyin.
Android Paketi Yapılandırın
Android'in çalışması için Android paket ayarlarını yapılandırmanız gerekiyor. Projenizin ".csproj" dosyasına Android paket yapılandırma dosyasını belirtmek için şu girişi ekleyin:
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
<AndroidBundleConfigurationFile>BundleConfig.json</AndroidBundleConfigurationFile>
Projede ana dizinde "BundleConfig.json" adında bir dosya oluşturun. Bu JSON dosyası, kütüphanenin işlevselliği için kritik olan Android paketinin gerekli ayarlarını içerir.
{
"optimizations": {
"uncompress_native_libraries": {}
}
}
Bu yapılandırma, yerel kütüphanelerin sıkıştırılmamış olduğundan emin olur, bu, kütüphanenin Android ortamında düzgün şekilde çalışması için gerekli bir adımdır.
Uygulama Arayüzünü Tasarlayın
Kullanıcılara barkod ve QR kodları üretmek için değerler girebileceği bir XAML dosyasını güncelleyin. Ayrıca bir belge seçmek için 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ı Okuyun ve Yazın
MainPage.xaml kodundan, üretilen barkod ve QR kodunun PDF formatında olup olmayacağını belirlemek için onay kutusunun karar verdiğini görebiliriz. Sonraki adım olarak lisans anahtarını ayarlayın. Bu adım için lütfen deneme ya da ücretli bir lisans anahtarı kullanın.
Kod, barcodeInput değişkenindeki değeri kontrol edip alır, ardından CreateBarcode yöntemini kullanarak BARCODE'ı oluşturur. Son olarak, hem Android hem de 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ın
Bu, projenin nasıl çalıştırılacağını ve barkod özelliğinin nasıl kullanılacağını gösterecektir.
.NET MAUI Uygulama Projesi İndirin
Bu kılavuzun tüm kodunu indirebilirsiniz. Visual Studio'da .NET MAUI Uygulama projesi olarak açabileceğiniz sıkıştırılmış bir dosya olarak gelir.
Sıkça Sorulan Sorular
.NET MAUI uygulamasında Android için barkodları nasıl oluşturabilir ve tarayabilirim?
.NET MAUI projesinde BarCode.Android paketini kullanarak Android cihazlarda barkod oluşturabilir ve tarayabilirsiniz. Bu, Visual Studio'da NuGet üzerinden paketin ayarlanmasını ve WriteBarcode ve ReadBarcode gibi sağlanan yöntemleri kullanarak barkod işlevselliklerini uygulamayı içerir.
Bir .NET MAUI projesinde Android için barkod işlevselliğini ayarlamak için hangi adımlar gereklidir?
.NET MAUI projesinde barkod işlevselliğini ayarlamak için NuGet kullanarak BarCode.Android paketini yükleyin, .csproj dosyanızı Android için koşullu olarak paketi dahil edecek şekilde yapılandırın ve Android paket konfigürasyonunuzu içine bir BundleConfig.json dosyası ile ayarlayın.
.csproj dosyasını sadece Android için barkod işlevselliğini içerecek şekilde nasıl yapılandırırım?
.csproj dosyasını, Android'i hedef alan bir koşul içeren 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ılmadan kalmasını sağlar. Bu, Android cihazlarında barkod kütüphanesinin düzgün çalışması için gereklidir.
.NET MAUI uygulamasında barkod işlemleri için bir arayüzü nasıl tasarlayabilirim?
Kullanıcıların barkodlar ve QR kodlar oluşturmak için veri girişi yapmasına olanak tanıyacak şekilde XAML kullanarak uygulama arayüzünü tasarlayın. Barkodları okumak için belgeleri seçme ve barkodları oluşturma, kaydetme ve tarama için butonlar ekleyin.
Bir uygulamada barkodlar oluşturmak ve okumak için C# yöntemleri nelerdir?
.NET MAUI uygulamasında, sırasıyla, dosyalardan barkod oluşturmak, QR kodlar oluşturmak ve okumak için WriteBarcode, WriteQRcode ve ReadBarcode yöntemlerini kullanın.
.NET MAUI uygulamamda barkod özelliklerini nasıl test edebilirim?
Projenizi gerekli yapılandırmalar ve barkod kodu uygulamaları ile ayarladıktan sonra, Android cihazında veya Visual Studio aracılığıyla bir emülatörde çalıştırarak özellikleri test edebilirsiniz.
Barkod işlevsellikleri ile tamamlanmış bir .NET MAUI Uygulama projesini nerede bulabilirim?
Barkod işlevsellikleri ile tamamlanmış bir .NET MAUI Uygulama projesi IronBarcode web sitesinden zip formatında indirilebilir. Bu proje daha fazla keşif ve özelleştirme için Visual Studio'da açılabilir.
Android projemde barkod kütüphanesini kullanmak için bir lisans gerekli mi?
Evet, projenizde barkod kütüphanesini kullanmak için bir deneme veya ödenmiş lisans anahtarı gereklidir. Bu anahtarı kütüphanenin özelliklerini etkinleştirmek için MainPage yapıcısında girmelisiniz.
IronBarcode, barkodların toplu işlenmesini destekliyor mu?
Evet, IronBarcode toplu işlemeyi destekler, bu da geliştiricilerin büyük ölçekli uygulamalar için verimliliği artırarak tek bir işlemde birden fazla barkod oluşturmasını veya okumasını sağlar.

