Hataları Nasıl Ele Alır ve C#'ta Barkod İşlemlerini Nasıl Hata Ayıklarım?

This article was translated from English: Does it need improvement?
Translated
View the article in English

Barkod işleme boru hatları sessizce başarısız olabilir, sıfır sonuç çoğu zaman 'barkod yok' olarak yanılgıya düşürülür. Ancak, bozuk dosyalar, parola korumalı PDF'ler veya format uyumsuzluğu gibi sorunlar sorumlu olabilir. Doğru günlükleme ve yapılandırılmış hata işleme, bu başarısızlıkları ortaya çıkarır ve eyleme geçirilebilir teşhisler sağlar.

IronBarcode, IronBarCode.Exceptions ad alanında yazılmış bir istisna hiyerarşisi, yerleşik bir günlükleme API'si ve ayrıntılı BarcodeResult özellikleri sunar. Bu özellikler, her başarılı decode için algılanan formatı, çözümlenen değeri, sayfa numarasını ve koordinatları içerir.

Bu eğitim, yazılmış istisnaları yakalamayı ve yorumlamayı, başarısız okumalardan teşhis bağlamı çıkarmayı, yapılandırılmış günlüklemeyi etkinleştirmeyi ve toplu işlemler sırasında hataları izole etmeyi açıklar.

Hızlı Başlangıç: Barkod Hatalarını Ele Alın ve Teşhisleri Etkinleştirin

Okuma/yazma çağrılarını, sessiz başarısızlıklar yerine eyleme geçirilebilir hata mesajları ortaya çıkarmak için IronBarcode'un yazılmış istisnalarını hedefleyen try-catch blokları içinde sarın.

  1. NuGet Paket Yöneticisi ile https://www.nuget.org/packages/BarCode yükleyin

    PM > Install-Package BarCode
  2. Bu kod parçasını kopyalayıp ç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}");
    }
  3. Canlı ortamınızda test etmek için dağıtın

    Bugün projenizde IronBarcode kullanmaya başlayın ücretsiz deneme ile

    arrow pointer

IronBarcode İstisnalarını Nasıl Yakalayıp Yorumlarım?

IronBarcode istisnalarını en özelden en genele doğru yakalayın. Eyleme geçirilebilir istisnaları (dosya, PDF parolası ve kodlama hataları gibi) ilk önce ardından temel türü ele alacak şekilde yakalama bloklarını sıraya koyun. IronBarCode.Exceptions ad alanı, her biri belirli bir hata moduna karşılık gelen 11 istisna türünü tanımlar:

IronBarcode İstisna Türleri — Nedenleri ve Önerilen Çözümler
İstisna TürüTetikleyiciÖnerilen Çözüm
IronBarCodeFileExceptionDosya bozuk, kilitli veya desteklenmeyen bir görüntü formatındaDosyanın desteklenen bir görüntü formatında ve kilitli olmadığını doğrulayın; ayrıca eksik dosyalar için FileNotFoundException'ı ayrı olarak yakalayın
IronBarCodePdfPasswordExceptionPDF parola korumalı veya şifrelenmişParolayı PdfBarcodeReaderOptions aracılığıyla sağlayın veya dosyayı atlayıp günlüğe kaydedin
IronBarCodeEncodingExceptionBarkod üretimi sırasında genel kodlama hatasıGiriş verilerinin hedef BarcodeWriterEncoding kısıtlamalarıyla eşleştiğini doğrulayın
IronBarCodeContentTooLongEncodingExceptionSeçilen semboloji için karakter limitini aşan değerVerileri kes veya daha yüksek kapasiteli bir formata geç (QR, DataMatrix)
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingExceptionSayısal olmayan karakterler sayısal formatlara (EAN, UPC) geçirildiGirişi temizle veya alfasayısal bir formata geç (Code128, Code39)
IronBarCodeUnsupportedRendererEncodingExceptionSeçili BarcodeEncoding, IronBarcode tarafından yazılamazBarcodeEncoding yerine BarcodeWriterEncoding enumunu kullanın
IronBarCodeParsingExceptionYapılandırılmış veri (GS1-128) ayrıştırma sırasında doğrulamadan geçemediAyrıştırmadan önce Code128GS1Parser.IsValid() ile GS1 yapısını doğrulayın
IronBarCodeNativeExceptionYerel ara katman hatası (eksik DLL'ler, platform uyumsuzluğu)Platforma özel NuGet paketlerinin yüklü olduğunu doğrulayın (BarCode.Linux, BarCode.macOS)
IronBarCodeConfidenceThresholdExceptionOkuyucu seçeneklerine geçersiz güven eşiği argümanı verildiConfidenceThreshold'ın 0.0 ile 1.0 arasında olduğundan emin olun
IronBarCodeUnsupportedExceptionMevcut bağlamda desteklenmeyen işlemGünlük değişiklikleri inceleyin, sürümünüzdeki özelliklerin kullanılabilirliği için
IronBarCodeExceptionTemel tür — yukarıda eşleşmemiş herhangi bir IronBarcode'a özel hatayı yakalarTam hata ayrıntılarını kaydedin ve araştırma için yükseltin

Kesişen istisna türlerini derin iç içe yerleştirme olmadan yönlendirmek için when hükümleriyle istisna filtreleri kullanın. Eksik dosyalar, IronBarCodeFileException yerine standart System.IO.FileNotFoundException fırlatır, bu yüzden bu durum için ayrı bir catch bloğu ekleyin:

Girdi

Bir fatura numarasını şifreleyen bir Code128 barkodu (başarı yolu) ve eksik PDF'in içeriğini temsil eden bir depo etiket barkodu (başarısızlık yolu).

Taradılan fatura girdisi olarak kullanılan INV-2024-7829 şifreleyen Code128 barkodu
Code128 barcode representing the content of the missing warehouse-labels.pdf failure path input
: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
$vbLabelText   $csharpLabel

Çıktı

Lütfen dikkate alinGeçerli bir dosya, çözümlenmiş barkod türü ve değerine çözülür.

Başarılı Code128 çözümlemesini gösteren konsol çıktısı: [Code128] INV-2024-7829

Eksik bir dosya, özel catch bloğuyla yönlendirilen FileNotFoundException'yi tetikler.

Eksik depo-etiketleri.pdf dosyası için FileNotFoundException'ı gösteren konsol çıktısı

when (ex.Message.Contains("DLL")) filtresi IronBarCodeNativeException üzerinde, eksik-bağımlılık hatalarını, diğer yerel istisnaları etkilemeden belirli bir işlemciye yönlendirir. Bu yaklaşım, platforma özgü paketlerin eksik olabileceği Docker dağıtımlarında özellikle yararlıdır.

Lisans anahtarı geçersiz veya eksik olduğunda, IronSoftware.Exceptions.LicensingException ayrı olarak fırlatılır. Bu istisnayı uygulama başlangıcında, bireysel okuma veya yazma çağrıları etrafında değil, yakalayın.


Başarısız Okumalardan Tanı Verilerini Nasıl Çıkarırım?

Sıfır sonuç döndüren bir okuma işlemi bir istisna değildir; boş bir BarcodeResults koleksiyonu üretir. Tanı bağlamı, giriş parametrelerini, yapılandırılmış seçenekleri ve döndürülen herhangi bir kısmi sonucu inceleyerek elde edilir.

BarcodeResult nesnesi, otopsi analizi için kullanışlı olan ve köşe koordinatlarını içeren BarcodeType, Value, PageNumber ve Points (kenar koordinatları) gibi özellikler sağlar. Sonuçlar varsa ama beklenmedikse, önce BarcodeType'yi beklenen formata karşı kontrol edin ve PageNumber'yi doğrulayın.

Girdi

Code128 ve QRCode olarak ayarlanmış ExpectBarcodeTypes ile okunan, hesap numarasını kodlayan bir Code128 barkodu ve kapsamlı tarama için ReadingSpeed.Detailed ile.

Taradılan fatura girdisi olarak kullanılan INV-2024-7829 şifreleyen Code128 barkodu
: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
$vbLabelText   $csharpLabel

Çıktı

Lütfen dikkate alin Görüntüdeki barkod ile ExpectBarcodeTypes eşleştiğinde, okuma türü, değeri, sayfa numarasını ve konumunu döndürür.

Sayfa numarası ve pozisyon koordinatları ile başarılı Code128 çözümlemesini gösteren konsol çıktısı

ExpectBarcodeTypes asıl semboloji içermiyorsa, okuma boş bir sonuç döner. [WARN] bloğu, yapılandırılan türleri, okuma hızını ve önerilen bir sonraki adımı kaydeder.

Code128 görüntüsü için Code39 olarak ayarlanmış ExpectBarcodeTypes ile barkod bulunamadığını gösteren WARN konsol çıktısı

Tanılama sırasında iki yaygın desen ortaya çıkar. Dar bir ExpectBarcodeTypes ayarı ile boş sonuçlar genellikle barkodun farklı bir semboloji kullandığı anlamına gelir; BarcodeEncoding.All'ye genişletmek bunu doğrulayabilir. Beklenmedik çözümleme sonuçları genellikle düşük görüntü kalitesine işaret eder.

Görüntü filtrelerini uygulamak ve daha yavaş bir okuma hızıyla tekrar denemek genellikle bu sorunları çözer. Gürültülü arka planlardan çıkmaları önlemek için RemoveFalsePositive seçeneğini de açıp kapatabilirsiniz.

Barkod İşlemleri için Ayrıntılı Günlük Kaydını Nasıl Etkinleştiririm?

IronBarcode, IronSoftware.Logger aracılığıyla yerleşik bir günlükleme API'si sunar. Okuma ve yazma kanallarından iç tanı çıktılarını yakalamak için herhangi bir barkod işlemleri öncesinde günlük kaydı modunu ve dosya yolunu ayarlayın.

Girdi

Ayrıntılı günlük kaydı aktifken okuma hedefi olarak kullanılan bir Code128 barkod TIFF görüntüsü.

Günlük kaydı örneği için problem tarama girdisi olarak kullanılan PROB-SCAN-999 şifreleyen Code128 barkodu
: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.")
$vbLabelText   $csharpLabel

LoggingModes.All hem hata ayıklama çıktısını hem de dosya düzeyinde günlüklemeyi yakalar. Günlük dosyası, genel API aracılığıyla görünmeyen resim ön işleme aşamaları, format algılama girişimleri ve yerel interop çağrıları gibi dahili işlem adımlarını kaydeder.

Yapısal günlükleme çerçevesi (Serilog, NLog, Microsoft.Extensions.Logging) kullanan üretim boru hatları için, IronBarcode işlemlerini bir ara katman tabakası içinde sarmak, yerleşik günlük dosyasının yanında yapılandırılmış JSON girişleri ekler. Yerleşik günlükleyici, destek tırmanışı için kullanışlı olan düz metin teşhisleri 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
$vbLabelText   $csharpLabel

Yapılandırılmış çıktı, günlük birleştirme araçlarıyla doğrudan bütünleşir. stdout'yi kapsayıcı dağıtımında Fluentd, Datadog veya CloudWatch'a yönlendirin. Geçen zaman alanı, SLA ihlali olmadan önce performans gerilemelerini vurgular.

Çıktı

Ayrıntılı günlük kaydı etkin ve günlük dosya yolu ile bir başarılı barkod okumasını gösteren konsol çıktısı

Yığın Barkod İşlemini Nasıl Hata Ayıklarım?

Her bir okuma kendi içinde bir try-catch bloğuna izole edilerek, her dosya için sonuçlar kaydedilir ve toplu bir özet üretilir. Boru hattı, ilk hata yerine hatalar yoluyla devam eder.

Girdi

scans/ yığın dizininden beş Code128 barkod resminden dördü. Beşinci dosya (scan-05-broken.png), bir dosya istisnasını tetiklemek için geçersiz baytlar içerir.

Code128 barcode encoding ITEM-SQ-001

Yığın 1 — Tarama 1

Code128 barcode encoding ITEM-SQ-002

Yığın 1 — Tarama 2

Code128 barcode encoding ITEM-SQ-003

Yığın 1 — Tarama 3

Code128 barcode encoding ITEM-SQ-004

Yığın 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
$vbLabelText   $csharpLabel

Çıktı

Bozuk dosya için hata ayrıntılarıyla birlikte, 4 başarı, 1 başarısızlık: toplu özetini gösteren konsol çıktısı

Yürütme sırasında, her çözümlenen barkod için bir satır, ardından dosya sayısı, başarı, boş okumalar, hatalar ve geçen süre ile bir özet konsola çıkar. Hatalar, karşılık gelen dosya adları ve hata nedenleri ile listelenmiştir.

Süreç üç sonuç kategorisini ayırt eder: başarı (barkodlar bulundu ve çözümlendi), boş (dosya okundu ancak barkod tespit edilmedi) ve hata (istisna atıldı). Bu ayırım önemlidir çünkü boş okumalar ve hatalar farklı yanıtlar gerektirir. Boş okumalar daha geniş format ayarları gerektirebilirken, hatalar genellikle eksik dosyalar, kilitli kaynaklar veya eksik yerel bağımlılıklar gibi altyapı sorunlarına işaret eder.

Hata listesi, kök neden analizi desteği sağlamak için dosya başına bağlamı korur. Bir CI/CD kanalı içinde, bu çıkışı çıkış kodları (tam başarı için sıfır ve failCount sıfırdan büyük olduğunda sıfır olmayan) ayarlamak için çevirin veya hata ayrıntılarını bir uyarı sistemine iletin.

Daha yüksek verimlilik için Multithreaded'yi true olarak ayarlayarak paralel işlemi etkinleştirin ve mevcut CPU çekirdeklerine uyum için MaxParallelThreads'yi ayarlayın. Her dosya için izolasyonu koruyarak paralel yinelemeyi Parallel.ForEach içerisinde sararak ve hata listesi için thread güvenli bir koleksiyon kullanarak.


Daha Fazla Okuma

Lisanslama seçeneklerini görün boru hattı üretime hazır olduğunda.

Sıkça Sorulan Sorular

IronBarcode kullanarak barkod işlemlerinde hatalari nasil yönetebilirim?

IronBarcode, barkod işlemlerindeki hatalari etkili bir şekilde yönetmek ve ele almak için tipi belirtilmis istisnalar ve yerlesen loglama saglar, boylece uygulamaniz sorunsuz calisir.

IronBarcode barkod sorunlarinin hata ayiklanmasi için hangi özellikleri sunar?

IronBarcode, tani çıkarimi ve uretim hazir kume hata izolasyonu icerir, bu da geliştiricilere barkod ile ilgili sorunlari verimli bir şekilde belirlemelerine ve cozmesine yardimci olur.

IronBarcode, barkod işleminde hatalari loglayabilirmi?

Evet, IronBarcode, geliştiricilerin barkod işleme sirasinda hata ayrintilarini yakalayip log tutmasina izin veren yerlesen loglama yeteneklerine sahiptir, bu da daha kolay bir hata ayiklama saglar.

IronBarcode'daki tipi belirli istisnalar nedir?

IronBarcode'daki tipi belirli istisnalar, barkod işlemiyle ilgili sorunlar hakkinda ayrintili bilgi saglayan özel hata turleridir, bu da geliştiricilerin sorunlari daha kolay teshis edip cozmelerini saglar.

IronBarcode, kume hata izolasyonuna nasil yardimci olur?

IronBarcode, hatalı barkod işlemlerini başarılı olanlardan ayırmaya yardımcı olan üretim geçerli parti hata izolasyonu sunar, böylece hata yönetimini parti işleme sürecinde kolaylaştırır.

IronBarcode kullanarak barkod işlemlerinden tanılama bilgilerini çıkarmanın bir yolu var mı?

Evet, IronBarcode, geliştiricilere barkod işlemleri hakkında ayrıntılı bilgi toplamaları için yardımcı olan tanılama çıkartma araçları sunar, bu da sorun giderme ve hata çözümüne yardımcı olur.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 2,169,908 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package BarCode
bir örnek çalıştırın dize barkod haline geldiğini görün.