C# ile Barkod İşlemlerinde Hatalar Nasıl Ele Alınır ve Hata Ayıklanır
Barkod işleme boru hatları sessizce başarısız olabilir, sonuçsuz sonuçlar çoğunlukla 'barkod yok' ile karıştırılır. Ancak, bozuk dosyalar, parola korumalı PDF'ler veya format uyumsuzlukları gibi sorunlar sorumlu olabilir. Doğru günlükleme ve yapılandırılmış hata yönetimini uygulamak bu aksaklıkları ortaya çıkartır ve eyleme geçirilebilir tanılama sağlar.
IronBarcode, IronBarCode.Exceptions ad alanında tipli bir istisna hiyerarşisi, yerleşik bir günlük kaydı API'si ve ayrıntılı BarcodeResult özellikleri sunar. Bu özellikler, algılanan format, çözümlü değer, sayfa numarası ve her başarılı çözümleme için koşulları içerir.
Bu nasıl yapılır, yazılı istisnaların nasıl yakalanacağını ve yorumlanacağını, başarısız okumalardan tanı teşhis bağlamının nasıl çıkarılacağını, yapılandırılmış kayıt tutmanın nasıl etkinleştirileceğini ve toplu işlemler sırasında hataların nasıl izole edileceğini açıklar.
Hızlı Başlangıc: Barkod Hataları Handle Et ve Tanılamalar Nasıl Etkinleştirilir
IronBarcode'un türlenmiş istisnalarına yönelik try-catch blokları içine okuma/yazma çağrılarını sararak sessiz başarısızlıklardan eyleme geçirilebilir hata mesajları ortaya çıkarın.
-
IronBarcode aşağıdaki NuGet Paket Yöneticisi ile yükleyin
PM > Install-Package BarCode -
Bu kod parçacığını kopyalayın ve çalıştırın.
using IronBarCode; using IronBarCode.Exceptions; try { BarcodeResults results = BarcodeReader.Read("label.pdf"); Console.WriteLine($"Found {results.Count} barcode(s)"); } catch (IronBarCodeFileException ex) { Console.Error.WriteLine($"File error: {ex.Message}"); } -
Canlı ortamınızda test için dağıtım yapın
Ücretsiz deneme ile bugün projenizde IronBarcode kullanmaya başlayın
IronBarcode ile Barkod Hatalarını Handle Etme ve Tanılamaları Etkinleşitme Yöntemleri
- IronBarcode kütüphanesini NuGet'ten indirin
- Belirli istisna türlerini hedefleyen try-catch blokları içine okuma/yazma çağırılarını sarın
- Başarılı bir okuma sonrası boş veya düşük güven girişleri için
BarcodeResultsinceleyin - İç tanı koyma çıkışını yakalamak için
IronSoftware.Logger'ı etkinleştirme - Devam ile hata üzeri devam mantığı ile toplu işlemlerde dosya başına başarısızlıkları izole edin
IronBarcode İstisnalarını Nasıl Yakalar ve Yorumlarsınız?
IronBarcode istisnalarını en ozelden genel olanına kadar yakalaın. Handle edilebilir istisnaların özetonları, dosya, PDF şifresi ve kodlama hataları gibi daha ardından ise türün genelini handle eden bloklara yerleştirin. IronBarCode.Exceptions ad alanı, her biri belirli bir hata moduna karşılık gelen 11 istisna türü tanımlar:
| İstisna Türü | Tetikleyici | Önerilen Çözüm |
|---|---|---|
IronBarCodeFileException | Dosya bozuk, kilitli veya desteklenmeyen bir resim formatında | Dosyanın desteklenen bir resim formatında olmadığını ve kilitli olmadığını doğrulayn; ayrıca kayıp dosyalar için ayrı bir FileNotFoundException ayrıca yakalayın |
IronBarCodePdfPasswordException | PDF parola korumalı veya şifreli | PdfBarcodeReaderOptions ile parola sağla, veya dosyayı atla ve kaydını tut |
IronBarCodeEncodingException | Barkod oluşturma süresinde genel kodlama başarısızlığı | Girdi verilerini hedef BarcodeWriterEncoding kısıtlamalarına uymacak şekilde doğrula |
IronBarCodeContentTooLongEncodingException | Seçilen semboloji için karakter limiti aşımı | Verileri kısalt veya daha yüksek kapasiteli bir formata geç (QR, DataMatrix) |
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException | Sadece sayısal bir formatı (EAN, UPC) içiğer ele geçirildiği karan terskarakterleri | Gürdüleri sanitize edin veya alfa-nümerik bir formata geç (Code128, Code39) |
IronBarCodeUnsupportedRendererEncodingException | Seçilen BarcodeEncoding, IronBarcode tarafından yazılamıyor | BarcodeWriterEncoding enum'u yerine BarcodeEncoding kullan |
IronBarCodeParsingException | Yapısal veriler (GS1-128) çözümleme sırasında doğrulanmakta başarısız olur | Code128GS1Parser.IsValid() ile GS1 yapısını doğrulayın ve sonrasında çözümleme yapın |
IronBarCodeNativeException | Yerel birlikte çalışma katmanında hata (eksik DLL'ler, platformun uyumsuzluğu) | Platforma özel NuGet paketlerinin kurulu olduğunuzu doğrulayın (BarCode.Linux, BarCode.macOS) |
IronBarCodeConfidenceThresholdException | Okuma seçeneklerine geçersiz güven eşiği bağımsız değişkeni geçirildi | ConfidenceThreshold'nin 0.0 ile 1.0 arasında olduğundan emin olun |
IronBarCodeUnsupportedException | Geçerli bağlamda desteklenmeyen bir işlem | Sürümde Özellik kullanılabilirliği için değişiklik günlüğünü kontrol edin |
IronBarCodeException | Temel tür — yukarıdaki ile eşleştirilmeyen herhangi bir IronBarcode'a özgü hatayı yakalar | Tam istisna ayrıntılarını kaydedin ve daha fazla denetimle üst yönetime aktarın |
Çakışan istisna türlerini derin iç içe geçme olmadan yönlendirmek için when cümleleriyle istisna filtreleri kullanın. Eksik dosyalar IronBarCodeFileException yerine standart System.IO.FileNotFoundException hatasını verir, bu nedenle bu durum için ayrı bir catch bloğu ekleyin:
Giriş
Bir Code128 barkodu, bir fatura numarasıný kodlayarak içeren ( başarı yolu) ve eksik PDF'nin içeriğini temsil ettiği bir depo etiketi barkodu
scanned-invoice.png (başarılı yol)
warehouse-labels.pdf (başarısız yol — dosya disk üzerinde yok)
:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/exception-hierarchy.cs
using IronBarCode;
using IronBarCode.Exceptions;
// Success path: valid file present on disk
string filePath = "scanned-invoice.png";
// Failure path: file does not exist → caught by FileNotFoundException below
// string filePath = "warehouse-labels.pdf";
try
{
BarcodeResults results = BarcodeReader.Read(filePath);
foreach (BarcodeResult result in results)
{
// Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}");
}
}
catch (IronBarCodePdfPasswordException ex)
{
// PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
// File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (FileNotFoundException ex)
{
// Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
// The when filter routes only missing-DLL errors here; other native exceptions
// fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
// Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}
Imports IronBarCode
Imports IronBarCode.Exceptions
' Success path: valid file present on disk
Dim filePath As String = "scanned-invoice.png"
' Failure path: file does not exist → caught by FileNotFoundException below
' Dim filePath As String = "warehouse-labels.pdf"
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath)
For Each result As BarcodeResult In results
' Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}")
Next
Catch ex As IronBarCodePdfPasswordException
' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
' File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As FileNotFoundException
' Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
' The when filter routes only missing-DLL errors here; other native exceptions
' fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
' Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End Try
Çıktı
Eksik bir dosya, özel catch bloğu tarafından yönlendirilen FileNotFoundException hatasını tetikler.
when (ex.Message.Contains("DLL")) üzerindeki IronBarCodeNativeException filtresi, eksik bağımlılık hatalarını diğer yerel istisnaları etkilemeden belirli bir işleyiciye yönlendirir. Bu yaklaşım, platforma özgü paketlerin eksik olabileceği Docker dağıtımlarında özellikle faydalıdır.
Lisans anahtarı geçersiz veya eksik olduğunda IronSoftware.Exceptions.LicensingException ayrı olarak atılır. Bu istisnayı bireysel okuma veya yazma çağrıları yerine uygulama başlangıcında yakalayın.
Başarısız Okumalardan Teşhis Detayları Nasıl Çıkarılır?
Sıfır sonuç döndüren bir okuma işlemi bir istisna değildir; boş bir BarcodeResults koleksiyonu üretir. Teşhis bağlamı, giriş parametreleri, yapılandırılmış seçenekler ve döndürülen herhangi bir kısmi sonuç incelenerek elde edilir.
BarcodeResult nesnesi, BarcodeType, Value, PageNumber ve Points (köşe koordinatları) dahil olmak üzere, post-mortem analizi için yararlı özellikler sağlar. Sonuçlar mevcut ancak beklenmedikse, önce BarcodeType'yi beklenen formatla karşılaştırın ve PageNumber'yi doğrulayın.
Giriş
Fatura numarasını kodlayan bir Code128 BARCODE, ExpectBarcodeTypes Code128 ve QRCode olarak ayarlanmış ve ReadingSpeed.Detailed ile kapsamlı tarama yapılmıştır.
:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/diagnostic-logging.cs
using IronBarCode;
string filePath = "scanned-invoice.png";
// Configure the reader to narrow the search to specific symbologies and use
// a thorough scan pass — narrows false positives and improves decode accuracy
var options = new BarcodeReaderOptions
{
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formats
Speed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged images
ExpectMultipleBarcodes = true // scan the full image rather than stopping at the first match
};
BarcodeResults results = BarcodeReader.Read(filePath, options);
// An empty result is not an exception — it means no barcode matched the configured options
if (results == null || results.Count == 0)
{
// Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}");
Console.Error.WriteLine($" Speed: {options.Speed}");
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
foreach (BarcodeResult result in results)
{
// Points contains the four corner coordinates of the barcode in the image;
// use the first corner as a representative position indicator
string pos = result.Points.Length > 0 ? $"{result.Points[0].X:F0},{result.Points[0].Y:F0}" : "N/A";
Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
+ $"(Page: {result.PageNumber}, Position: {pos})");
}
}
Imports IronBarCode
Dim filePath As String = "scanned-invoice.png"
' Configure the reader to narrow the search to specific symbologies and use
' a thorough scan pass — narrows false positives and improves decode accuracy
Dim options As New BarcodeReaderOptions With {
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit scan to known formats
.Speed = ReadingSpeed.Detailed, ' slower but more thorough — use ExtremeDetail for damaged images
.ExpectMultipleBarcodes = True ' scan the full image rather than stopping at the first match
}
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
' An empty result is not an exception — it means no barcode matched the configured options
If results Is Nothing OrElse results.Count = 0 Then
' Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}")
Console.Error.WriteLine($" Speed: {options.Speed}")
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
For Each result As BarcodeResult In results
' Points contains the four corner coordinates of the barcode in the image;
' use the first corner as a representative position indicator
Dim pos As String = If(result.Points.Length > 0, $"{result.Points(0).X:F0},{result.Points(0).Y:F0}", "N/A")
Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
$"(Page: {result.PageNumber}, Position: {pos})")
Next
End If
Çıktı
ExpectBarcodeTypes, görüntüdeki BARCODE ile eşleştiğinde, okuma işlemi türü, değeri, sayfa numarasını ve konumu döndürür.
ExpectBarcodeTypes gerçek sembolojiyi içermiyorsa, okuma işlemi boş bir sonuç döndürür. [WARN] bloğu, yapılandırılan türleri, okuma hızını ve önerilen bir sonraki eylemi kaydeder.
Teşhis sırasında iki yaygın model ortaya çıkar. Dar bir ExpectBarcodeTypes ayarıyla boş sonuçlar genellikle BARCODE'un farklı bir semboloji kullandığı anlamına gelir; BarcodeEncoding.All'ye genişletilerek bu durum doğrulanabilir. Beklenmeyen çözümleme sonuçları genellikle kötü görüntü kalitesine işaret eder.
Görüntü filtrelerini uygulamak ve daha yavaş bir okuma hızı ile tekrar denemek genellikle bu sorunları çözer. Ayrıca, RemoveFalsePositive seçeneğini etkinleştirerek gürültülü arka planlardan kaynaklanan hayali okumaları ortadan kaldırabilirsiniz.
Barkod İşlemleri İçin Ayrıntılı Günlüğü Nasıl Etkinleştiririm?
IronBarcode, IronSoftware.Logger aracılığıyla yerleşik bir günlük kaydı API'si sunar. Okuma ve yazma hatlarından gelen dahili teşhis çıktısını yakalamak için herhangi bir barkod işleminden önce günlük modunu ve dosya yolunu ayarlayın.
Giriş
Ayrıntılı günlüğün etkin olduğu sırada okuma hedefi olarak kullanılan bir Code128 barkod TIFF görüntüsü.
:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/enable-logging.cs
using IronBarCode;
// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
// LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"; // path is relative to the working directory
// All subsequent operations will write internal processing steps to the log file:
// image pre-processing stages, format detection attempts, and native interop calls
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Detailed,
ExpectBarcodeTypes = BarcodeEncoding.All // scan for every supported symbology
};
BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");
Imports IronBarCode
' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
' LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log" ' path is relative to the working directory
' All subsequent operations will write internal processing steps to the log file:
' image pre-processing stages, format detection attempts, and native interop calls
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Detailed,
.ExpectBarcodeTypes = BarcodeEncoding.All ' scan for every supported symbology
}
Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")
LoggingModes.All hem hata ayıklama çıktısını hem de dosya düzeyinde günlüğü yakalar. Günlük dosyası, genel API üzerinden görünmeyen görüntü ön işleme aşamaları, format algılama girişimleri ve yerel birlikte çalışabilirlik çağrıları gibi dahili işleme adımlarını kaydeder.
Yapılandırılmış bir günlükleme çerçevesi (Serilog, NLog, Microsoft.Extensions.Logging) kullanan üretim boru hatları için, IronBarcode işlemlerini bir ara yazılım katmanına sarmak, yerleşik günlük dosyasına ek olarak yapılandırılmış JSON girişleri ekler. Yerleşik günlükleyici, destek eskalasyonu için yararlı olan düz metin tanılama bilgilerini yazar; yapılandırılmış sarıcı, gözlemlenebilirlik yığını için sorgulanabilir alanlar sağlar.
:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/structured-wrapper.cs
using IronBarCode;
using System.Diagnostics;
// Lightweight wrapper that adds structured JSON observability to every read call.
// Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
var sw = Stopwatch.StartNew(); // start timing before the read so setup overhead is included
try
{
BarcodeResults results = BarcodeReader.Read(filePath, options);
sw.Stop();
// Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
+ $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
return results;
}
catch (Exception ex)
{
sw.Stop();
// Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
+ $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
+ $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
throw; // rethrow so the caller's catch blocks still handle the exception normally
}
}
Imports IronBarCode
Imports System.Diagnostics
' Lightweight wrapper that adds structured JSON observability to every read call.
' Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
Dim sw As Stopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is included
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
sw.Stop()
' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Return results
Catch ex As Exception
sw.Stop()
' Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Throw ' rethrow so the caller's catch blocks still handle the exception normally
End Try
End Function
Yapılandırılmış çıktı, günlük toplama araçlarıyla doğrudan bütünleşir. Konteyner tabanlı bir dağıtımda stdout'yi Fluentd, Datadog veya CloudWatch'a aktarın. Geçen zaman alanı, SLA ihlalleri olmadan önce performans gerilemelerini vurgular.
Çıktı
Toplu Barkod İşleme Nasıl Hata Ayıklanır?
Her bir okuma işlemini kendi try-catch bloğuna izole ederek birden fazla dosya işleyin, her dosya için sonuçları kaydedin ve toplu bir özet oluşturun. İlk hata noktasında durmak yerine, ardışık süreç hatalar üzerinden devam eder.
Giriş
scans/ toplu iş dizinindeki beş Code128 BARCODE görüntüsünden dördü. Beşinci dosya (scan-05-broken.png) dosya istisnasını tetikleyecek geçersiz baytlar içeriyor.
Toplu 1 — Tarama 1
Toplu 1 — Tarama 2
Toplu 1 — Tarama 3
Toplu 1 — Tarama 4
:path=/static-assets/barcode/content-code-examples/how-to/detailed-error-messages/batch-processing.cs
using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;
// Enable built-in logging for the entire batch run so internal processing steps
// are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";
// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced, // balances throughput vs accuracy
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formats
ExpectMultipleBarcodes = true // scan each file fully
};
// Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>(); // per-file error context for root cause analysis
var sw = Stopwatch.StartNew();
foreach (string file in files)
{
try
{
BarcodeResults results = BarcodeReader.Read(file, options);
// Empty result is not an exception — the file was read but contained no matching barcode
if (results == null || results.Count == 0)
{
emptyCount++;
errors.Add((file, "No barcodes detected")); // record so caller can adjust options
continue;
}
foreach (BarcodeResult result in results)
{
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}");
}
successCount++;
}
catch (IronBarCodePdfPasswordException)
{
// PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount++;
errors.Add((file, "Password-protected PDF"));
}
catch (IronBarCodeFileException ex)
{
// File is corrupted, locked, or in an unsupported image format
failCount++;
errors.Add((file, $"File error: {ex.Message}"));
}
catch (FileNotFoundException ex)
{
// File was in the directory listing but deleted before the read completed (race condition)
failCount++;
errors.Add((file, $"File not found: {ex.Message}"));
}
catch (IronBarCodeException ex)
{
// Catch-all for any other IronBarcode-specific errors not handled above
failCount++;
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
}
catch (Exception ex)
{
// Unexpected non-IronBarcode error — log the full type for investigation
failCount++;
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
}
}
sw.Stop();
// Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files: {files.Length}");
Console.WriteLine($"Success: {successCount}");
Console.WriteLine($"Empty reads: {emptyCount}");
Console.WriteLine($"Failures: {failCount}");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s");
if (errors.Any())
{
Console.WriteLine("\n--- Error Details ---");
foreach (var (errorFile, errorMsg) in errors)
{
Console.Error.WriteLine($" {Path.GetFileName(errorFile)}: {errorMsg}");
}
}
Imports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
' Enable built-in logging for the entire batch run so internal processing steps
' are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"
' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit to known formats
.ExpectMultipleBarcodes = True ' scan each file fully
}
' Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))() ' per-file error context for root cause analysis
Dim sw As Stopwatch = Stopwatch.StartNew()
For Each file As String In files
Try
Dim results As BarcodeResults = BarcodeReader.Read(file, options)
' Empty result is not an exception — the file was read but contained no matching barcode
If results Is Nothing OrElse results.Count = 0 Then
emptyCount += 1
errors.Add((file, "No barcodes detected")) ' record so caller can adjust options
Continue For
End If
For Each result As BarcodeResult In results
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}")
Next
successCount += 1
Catch ex As IronBarCodePdfPasswordException
' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount += 1
errors.Add((file, "Password-protected PDF"))
Catch ex As IronBarCodeFileException
' File is corrupted, locked, or in an unsupported image format
failCount += 1
errors.Add((file, $"File error: {ex.Message}"))
Catch ex As FileNotFoundException
' File was in the directory listing but deleted before the read completed (race condition)
failCount += 1
errors.Add((file, $"File not found: {ex.Message}"))
Catch ex As IronBarCodeException
' Catch-all for any other IronBarcode-specific errors not handled above
failCount += 1
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
Catch ex As Exception
' Unexpected non-IronBarcode error — log the full type for investigation
failCount += 1
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
End Try
Next
sw.Stop()
' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files: {files.Length}")
Console.WriteLine($"Success: {successCount}")
Console.WriteLine($"Empty reads: {emptyCount}")
Console.WriteLine($"Failures: {failCount}")
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s")
If errors.Any() Then
Console.WriteLine(vbCrLf & "--- Error Details ---")
For Each errorDetail In errors
Console.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
Next
End If
Çıktı
Çalışma sırasında, her çözümlenmiş barkod için bir satır ve ardından dosya sayısı, başarılar, boş okumalar, başarısızlıklar ve geçen süre ile bir özet çıktısı konsola yazılır. Hatalar, ilgili dosya adları ve hata nedenleri ile listelenir.
Bu işlem üç sonuç kategorisini ayırt eder: başarı (bulunan ve çözümlenen barkodlar), boş (dosya okundu ama barkod algılanmadı) ve başarısızlık (istisna atıldı). Bu ayrım önemlidir çünkü boş okumalar ve başarısızlıklar farklı yanıtlar gerektirir. Boş okumalar daha geniş format ayarları gerektirebilirken, başarısızlıklar genellikle eksik dosyalar, kilitli kaynaklar veya eksik yerel bağımlılıklar gibi altyapı sorunlarına işaret eder.
Hata listesi, kök neden analizini desteklemek için dosya başına bağlamı korur. Bir CI/CD boru hattında, bu çıktıyı ayrıştırarak çıkış kodlarını ayarlayın (tamamen başarılı olduğunda sıfır, failCount sıfırdan büyük olduğunda sıfırdan farklı) veya hata ayrıntılarını bir uyarı sistemine iletin.
Daha yüksek verim için, Multithreaded değerini true olarak ayarlayarak ve MaxParallelThreads değerini mevcut CPU çekirdeklerine uyacak şekilde ayarlayarak paralel işlemeyi etkinleştirin. Paralel yinelemeyi Parallel.ForEach ile sararak ve hata listesi için iş parçacığı güvenli bir koleksiyon kullanarak dosya başına izolasyonu koruyun.
Daha Fazla Okuma
- IronBarcode Eğiticiler: Barkodları Okuma: uçtan uca okuma adımları.
- Yanlış Pozitif Önleme: gürültülü görüntülerde hayalet okumaları azaltma.
- Görüntü Düzeltme Nasıl Yapılır: okuma doğruluğunu artıran filtreler.
- Docker Kurulum Kılavuzu: doğru yerel bağımlılıklara sahip konteyner dağıtım.
- BarcodeReaderOptions API Referansı: tam yapılandırma belgeleri.
- IronBarcode Değişiklik Günlüğü: sürüme özel düzeltmeler ve özellik eklemeleri.
Lisans seçeneklerini görüntüleyin hattı üretim için hazır olduğunda.
Sıkça Sorulan Sorular
IronBarcode kullanarak barkod işlemlerinde hataları nasıl yönetebilirim?
IronBarcode, uygulamanızın sorunsuz çalışmasını sağlamak için barkod işlemlerinde hataları etkin bir şekilde yönetmek ve ele almak için tip tanımlı hatalar ve yerleşik günlüğe alma imkanı sağlar.
IronBarcode, barkod problemlerinin giderilmesi için hangi özellikleri sunuyor?
IronBarcode, geliştiricilerin barkodla ilgili sorunları verimli bir şekilde tanımlayıp çözmesini sağlayan teşhis çıkartımı ve üretime hazır toplu hata yalıtımı içerir.
IronBarcode, barkod işlemleri sırasında hataları kaydedebilir mi?
Evet, IronBarcode, geliştiricilerin barkod işleme sırasında hata detaylarını yakalayıp kaydetmelerine olanak tanıyan yerleşik günlüğe alma yeteneklerine sahiptir, böylece daha kolay hata ayıklama sağlar.
IronBarcode'da tip tanımlı hatalar nelerdir?
IronBarcode'daki tip tanımlı hatalar, barkod işlem sorunları hakkında ayrıntılı bilgiler sunan özel hata türleridir, bu da geliştiricilerin problemleri teşhis etmesini ve çözmesini kolaylaştırır.
IronBarcode toplu hata yalıtımına nasıl yardımcı olur?
IronBarcode, toplu hata yalıtımı yoluyla üretime hazır çözümler sunar, bu da hatalı barkod işlemlerini başarılı olanlardan ayırarak toplu işleme hata yönetimini sağlar.
IronBarcode kullanarak barkod işlemlerinden teşhisleri çıkartabilir miyim?
Evet, IronBarcode, geliştiricilerin barkod işlemleriyle ilgili ayrıntılı bilgileri toplamasına ve sorun gidermelerine yardımcı olan teşhis çıkartım araçları sağlar.
IronBarcode barkod görünümünü özelleştirme desteği sağlıyor mu?
Evet, IronBarcode, barkod görünümünü özelleştirmek için renk, boyut ve metin notları gibi geniş seçenekler sunar, bu da barkodları belirli tasarım gereksinimlerinize göre uyarlamanıza imkan tanır.
IronBarcode, iş süreçlerindeki verimliliği artırmaya nasıl yardımcı olabilir?
IronBarcode, hızlı ve doğru barkod üretimi ve okuma yeteneği sağlayarak, manuel veri girişi hatalarını azaltır ve envanter ile varlık takibini iyileştirerek iş süreçlerinin verimliliğini artırır.
Bir projede IronBarcode'u uygulamak için hangi programlama becerileri gereklidir?
IronBarcode'u bir projede uygulamak için temel C# programlama bilgisi yeterlidir, çünkü bu kütüphane, geliştiricilere rehberlik eden basit yöntemler ve kapsamlı belgeler sağlar.
IronBarcode, hem küçük projeler hem de büyük kurumsal uygulamalar için uygun mu?
IronBarcode, küçük projeler kadar geniş çaplı kurumsal uygulamalar için de uygun, ölçeklenebilir ve çok yönlü olacak şekilde tasarlanmıştır ve sağlam barkod çözümleri gerektiren uygulamalara hizmet eder.

