# Wie man Fehler behandelt und Barcode-Operationen in C# debuggt
Barcode-Verarbeitungssysteme können unbemerkt ausfallen, wobei Null-Ergebnisse oft fälschlicherweise als "kein Barcode vorhanden" interpretiert werden. Ursachen können jedoch beispielsweise beschädigte Dateien, passwortgeschützte PDFs oder Formatabweichungen sein. Durch die Implementierung einer ordnungsgemäßen Protokollierung und einer strukturierten Fehlerbehandlung werden diese Fehler aufgedeckt und umsetzbare Diagnoseinformationen bereitgestellt.
IronBarcode bietet eine typsichere Ausnahme-Hierarchie im `IronBarCode.Exceptions`-Namespace, eine eingebaute Logging-API und detaillierte `BarcodeResult`-Eigenschaften. Zu diesen Eigenschaften gehören das erkannte Format, der dekodierte Wert, die Seitenzahl und die Koordinaten für jede erfolgreiche Dekodierung.
Diese Anleitung erklärt, wie man typisierte Ausnahmen abfängt und interpretiert, diagnostischen Kontext von fehlgeschlagenen Lesevorgängen extrahiert, strukturiertes Logging aktiviert und Fehler während Batch-Operationen isoliert.
*as-heading:2(Schnellstart: Barcode-Fehler behandeln und Diagnose aktivieren)*
Um Lese-/Schreibaufrufe in try-catch-Blöcke einzuschließen, die auf die typisierten Ausnahmen von IronBarcode abzielen, werden aussagekräftige Fehlermeldungen anstelle stillschweigender Fehler angezeigt.
```cs
:title=Handle Barcode Errors and Enable Diagnostics
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}");
}
```
<div class="hsg-featured-snippet">
<h2>Wie man Barcode-Fehler behebt und die Diagnose mit IronBarcode aktiviert</h2>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/BarCode/">Laden Sie die IronBarcode Bibliothek von NuGet herunter.</a></li>
<li>Schließen Sie Lese-/Schreibaufrufe in try-catch-Blöcke ein, die auf bestimmte Ausnahmetypen abzielen.</li>
<li>Prüfen Sie <code>BarcodeResults</code> nach einem erfolgreichen Lesevorgang auf leere Einträge oder Einträge mit geringer Zuverlässigkeit.</li>
<li>Aktivieren Sie <code>IronSoftware.Logger</code> , um interne Diagnoseausgaben zu erfassen.</li>
<li>Fehler in Stapelverarbeitungen pro Datei mit einer "Fortsetzen bei Fehler"-Logik isolieren</li>
</ol>
</div>
## Wie fange ich IronBarcode Ausnahmen ab und interpretiere sie?
Fangen Sie IronBarcode Ausnahmen von den spezifischsten bis zu den allgemeinsten ab. Ordnen Sie die Catch-Blöcke so an, dass zuerst die Ausnahmen behandelt werden, die zu Aktionen führen, wie z. B. Datei-, PDF-Passwort- und Kodierungsfehler, gefolgt vom Basistyp. Der `IronBarCode.Exceptions`-Namespace definiert 11 Ausnahmetypen, die jeweils einem bestimmten Fehlermodus entsprechen:
<div class="content__data-table" data-content-table>
<table>
<caption>IronBarcode Ausnahmetypen – Ursachen und empfohlene Lösungen</caption>
<thead>
<tr><th>Ausnahmetyp</th><th>Auslösen</th><th>Empfohlene Lösung</th></tr>
</thead>
<tbody>
<tr><td><code>IronBarCodeFileException</code></td><td>Die Datei ist beschädigt, gesperrt oder liegt in einem nicht unterstützten Bildformat vor.</td><td>Prüfen Sie, ob die Datei ein unterstütztes Bildformat aufweist und nicht gesperrt ist; fangen Sie außerdem <code>FileNotFoundException</code> für fehlende Dateien separat ab.</td></tr>
<tr><td><code>IronBarCodePdfPasswordException</code></td><td>Die PDF-Datei ist passwortgeschützt oder verschlüsselt.</td><td>Geben Sie das Passwort über <code>PdfBarcodeReaderOptions</code> an oder überspringen Sie die Datei und das Protokoll.</td></tr>
<tr><td><code>IronBarCodeEncodingException</code></td><td>Fehler bei der allgemeinen Codierung während der Barcode-Generierung</td><td>Überprüfen, ob die Eingabedaten den Zielvorgaben <code>BarcodeWriterEncoding</code> entsprechen.</td></tr>
<tr><td><code>IronBarCodeContentTooLongEncodingException</code></td><td>Der Wert überschreitet die Zeichenbegrenzung für die ausgewählte Symbolisierung.</td><td>Daten kürzen oder auf ein Format mit höherer Kapazität (QR, DataMatrix) umstellen</td></tr>
<tr><td><code>IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException</code></td><td>Nicht-numerische Zeichen werden in ein rein numerisches Format (EAN, UPC) umgewandelt.</td><td>Eingabe bereinigen oder auf ein alphanumerisches Format umstellen (Code128, Code39).</td></tr>
<tr><td><code>IronBarCodeUnsupportedRendererEncodingException</code></td><td>Die ausgewählte <code>BarcodeEncoding</code> kann von IronBarcode nicht beschrieben werden.</td><td>Verwenden Sie die Enumeration <code>BarcodeWriterEncoding</code> anstelle von <code>BarcodeEncoding</code></td></tr>
<tr><td><code>IronBarCodeParsingException</code></td><td>Strukturierte Daten (GS1-128) können während der Analyse nicht validiert werden.</td><td>Die GS1-Struktur sollte vor dem Parsen mit <code>Code128GS1Parser.IsValid()</code> validiert werden.</td></tr>
<tr><td><code>IronBarCodeNativeException</code></td><td>Fehler in der nativen Interop-Schicht (fehlende DLLs, Plattforminkompatibilität)</td><td>Prüfen Sie, ob die plattformspezifischen NuGet Pakete installiert sind (BarCode.Linux, BarCode.macOS).</td></tr>
<tr><td><code>IronBarCodeConfidenceThresholdException</code></td><td>Ungültiges Argument für den Konfidenzschwellenwert an die Leseroptionen übergeben</td><td>Stellen Sie sicher, dass <code>ConfidenceThreshold</code> zwischen 0,0 und 1,0 liegt.</td></tr>
<tr><td><code>IronBarCodeUnsupportedException</code></td><td>Dieser Vorgang wird im aktuellen Kontext nicht unterstützt.</td><td>Prüfen Sie im <a href="https://ironsoftware.com/csharp/barcode/product-updates/changelog/">Änderungsprotokoll</a> , ob die Funktionen in Ihrer Version verfügbar sind.</td></tr>
<tr><td><code>IronBarCodeException</code></td><td>Basistyp – fängt alle IronBarcode-spezifischen Fehler ab, die oben nicht abgeglichen wurden</td><td>Protokollieren Sie alle Ausnahmedetails und eskalieren Sie diese zur Untersuchung.</td></tr>
</tbody>
</table>
</div>
Verwenden Sie Ausnahmefilter mit `when`-Klauseln, um überlappende Ausnahmetypen ohne tiefes Schachteln zu leiten. Fehlende Dateien werfen den Standard-`System.IO.FileNotFoundException` anstelle von `IronBarCodeFileException`, daher fügen Sie einen separaten catch-Block für diesen Fall hinzu:
### Eingabe
Ein Code128-Barcode, der eine Rechnungsnummer kodiert (Erfolgspfad), und ein Lageretiketten-Barcode, der den Inhalt der fehlenden PDF-Datei darstellt (Fehlerpfad).
<div class="competitors-section__wrapper-even-1">
<div class="competitors__card" style="width: 45%;">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-invoice.png"
alt="Code128-Barcode-Codierung INV-2024-7829 wurde als Eingabe für die gescannte Rechnung verwendet."
class="img-responsive add-shadow" />
<p class="competitors__download-link" style="color: #181818; font-style: italic;">
scanner-invoice.png (Erfolgspfad)
</p>
</div>
<div class="competitors__card" style="width: 45%;">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-warehouse-labels.png"
alt="Code128-Barcode, der den Inhalt der fehlenden warehouse-labels.pdf als Eingabe für den Fehlerpfad darstellt"
class="img-responsive add-shadow" />
<p class="competitors__download-link" style="color: #181818; font-style: italic;">
warehouse-labels.pdf (Fehlerpfad – Datei nicht auf der Festplatte vorhanden)
</p>
</div>
</div>
```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}");
}
```
### Ausgabe
[[i:(Eine gültige Datei wird zum dekodierten Barcode-Typ und -Wert aufgelöst.)]]
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-success.webp" alt="Konsolenausgabe mit erfolgreicher Code128-Dekodierung: [Code128] INV-2024-7829" class="img-responsive add-shadow" />
</div>
</div>
Eine fehlende Datei löst `FileNotFoundException` aus, das durch den dedizierten catch-Block geleitet wird.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-failure.webp" alt="Konsolenausgabe mit der Meldung "FileNotFoundException" für die fehlende Datei "warehouse-labels.pdf"." class="img-responsive add-shadow" />
</div>
</div>
Der `when (ex.Message.Contains("DLL"))`-Filter auf `IronBarCodeNativeException` leitet fehlende Abhängigkeitsfehler an einen speziellen Handler, ohne andere native Ausnahmen zu beeinflussen. Dieser Ansatz ist besonders nützlich bei Docker-Bereitstellungen, bei denen plattformspezifische Pakete fehlen könnten.
`IronSoftware.Exceptions.LicensingException` wird separat geworfen, wenn der Lizenzschlüssel ungültig oder fehlend ist. Fangen Sie diese Ausnahme beim Start der Anwendung ab, anstatt bei einzelnen Lese- oder Schreibaufrufen.
---
## Wie extrahiere ich Diagnosedetails aus fehlgeschlagenen Lesevorgängen?
Ein Lesevorgang, der kein Ergebnis liefert, stellt keine Ausnahme dar; es erzeugt eine leere `BarcodeResults`-Sammlung. Der Diagnosekontext wird durch die Prüfung der Eingabeparameter, der konfigurierten Optionen und etwaiger zurückgegebener Teilergebnisse ermittelt.
Das `BarcodeResult`-Objekt bietet Eigenschaften, die nützlich für die nachträgliche Analyse sind, einschließlich `BarcodeType`, `Value`, `PageNumber` und `Points` (Eckkoordinaten). Wenn Ergebnisse vorhanden, aber unerwartet sind, überprüfen Sie zuerst `BarcodeType` gegen das erwartete Format und verifizieren Sie `PageNumber`.
### Eingabe
Ein Code128-Barcode, der eine Rechnungsnummer kodiert, wird mit `ExpectBarcodeTypes` auf `Code128` gesetzt und `QRCode` sowie `ReadingSpeed.Detailed` für gründliches Scannen gelesen.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-invoice.png" alt="Code128-Barcode-Codierung INV-2024-7829 wurde als Eingabe für die gescannte Rechnung verwendet." class="img-responsive add-shadow" />
</div>
</div>
```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})");
}
}
```
### Ausgabe
[[i:(Wenn `ExpectBarcodeTypes` mit dem Barcode im Bild übereinstimmt, gibt das Lesen den Typ, den Wert, die Seitennummer und die Position zurück.)]]
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-success.webp" alt="Konsolenausgabe mit erfolgreicher Code128-Dekodierung, Seitenzahl und Positionskoordinaten" class="img-responsive add-shadow" />
</div>
</div>
Wenn `ExpectBarcodeTypes` die tatsächliche Symbologie nicht enthält, gibt das Lesen ein leeres Ergebnis zurück. Der [WARN]-Block protokolliert die konfigurierten Typen, die Lesegeschwindigkeit und eine vorgeschlagene nächste Aktion.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-failure.webp" alt="Konsolenausgabe mit der Meldung: [WARN] Es wurden keine Barcodes gefunden, wenn ExpectBarcodeTypes auf Code39 für ein Code128-Bild gesetzt ist." class="img-responsive add-shadow" />
</div>
</div>
Bei der Diagnostik lassen sich zwei häufige Muster erkennen. Leere Ergebnisse mit einer engen `ExpectBarcodeTypes`-Einstellung bedeuten oft, dass der Barcode eine andere Symbologie verwendet; die Erweiterung auf `BarcodeEncoding.All` kann dies bestätigen. Unerwartete Dekodierungsergebnisse deuten in der Regel auf eine schlechte Bildqualität hin.
Das Anwenden von Bildfiltern und ein erneuter Versuch mit einer langsameren Lesegeschwindigkeit beheben diese Probleme oft. Sie können auch die `RemoveFalsePositive`-Option umschalten, um Phantomlesungen von unruhigen Hintergründen zu eliminieren.
## Wie aktiviere ich die ausführliche Protokollierung für Barcode-Operationen?
IronBarcode bietet eine eingebaute Logging-API über `IronSoftware.Logger`. Legen Sie vor jeglichen Barcode-Operationen den Protokollierungsmodus und den Dateipfad fest, um interne Diagnoseausgaben aus den Lese- und Schreibpipelines zu erfassen.
### Eingabe
Als Leseziel wird ein Code128-Barcode-TIFF-Bild verwendet, während die ausführliche Protokollierung aktiviert ist.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-problem-scan.png" alt="Code128-Barcode-Codierung PROB-SCAN-999 wurde als Problemscan-Eingabe für das Protokollierungsbeispiel verwendet." class="img-responsive add-shadow" />
</div>
</div>
```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.");
```
`LoggingModes.All` erfasst sowohl Debug-Ausgaben als auch logging auf Dateiebene. Die Protokolldatei zeichnet interne Verarbeitungsschritte auf, wie z. B. Vorverarbeitungsphasen von Bildern, Versuche zur Formaterkennung und native Interop-Aufrufe, die über die öffentliche API nicht sichtbar sind.
Für Produktionspipelines mit einem strukturierten Logging-Framework (Serilog, NLog, `Microsoft.Extensions.Logging`) fügt das Einbinden von IronBarcode-Operationen in eine Middleware-Schicht strukturierte JSON-Einträge neben der eingebauten Protokolldatei hinzu. Der eingebaute Logger schreibt Diagnosen im Klartext, die für die Unterstützungseskalation nützlich sind; Der strukturierte Wrapper stellt abfragbare Felder für den Observability-Stack bereit.
```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
}
}
```
Die strukturierte Ausgabe lässt sich direkt in Log-Aggregationswerkzeuge integrieren. Leiten Sie `stdout` in einer containerisierten Bereitstellung an Fluentd, Datadog oder CloudWatch weiter. Das Feld "Verstrichene Zeit" hebt Leistungseinbußen hervor, bevor diese zu SLA-Verletzungen führen.
### Ausgabe
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-enable-logging.webp" alt="Konsolenausgabe, die einen erfolgreichen Barcode-Lesevorgang mit aktivierter ausführlicher Protokollierung und den Pfad zur Protokolldatei anzeigt" class="img-responsive add-shadow" />
</div>
</div>
---
## Wie kann ich die Stapelverarbeitung von Barcodes debuggen?
Mehrere Dateien werden verarbeitet, indem jeder Lesevorgang in einem eigenen try-catch-Block isoliert wird, die Ergebnisse für jede Datei werden aufgezeichnet und eine zusammenfassende Gesamtfassung erstellt. Die Pipeline wird trotz Ausfällen fortgesetzt, anstatt beim ersten Fehler anzuhalten.
### Eingabe
Vier der fünf Code128-Barcode-Bilder aus dem `scans/`-Batch-Verzeichnis. Die fünfte Datei (`scan-05-broken.png`) enthält ungültige Bytes, um eine Dateiausnahme auszulösen.
<div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
<div class="content-img-align-center" style="width: 22.5%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-batch-scan-one.png"
alt="Code128 barcode encoding ITEM-SQ-001"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">Charge 1 - Scan 1</p>
</div>
</div>
<div class="content-img-align-center" style="width: 22.5%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-batch-scan-two.png"
alt="Code128 barcode encoding ITEM-SQ-002"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">Stapel 1 - Scan 2</p>
</div>
</div>
<div class="content-img-align-center" style="width: 22.5%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-batch-scan-three.png"
alt="Code128 barcode encoding ITEM-SQ-003"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">Stapel 1 - Scan 3</p>
</div>
</div>
<div class="content-img-align-center" style="width: 22.5%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/input-batch-scan-four.png"
alt="Code128 barcode encoding ITEM-SQ-004"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">Stapel 1 - Scan 4</p>
</div>
</div>
</div>
```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}");
}
}
```
### Ausgabe
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/detailed-error-messages/output-batch-processing.webp" alt="Konsolenausgabe mit der Zusammenfassung des Batch-Vorgangs: 4 Erfolge, 1 Fehler, mit Fehlerdetails für die beschädigte Datei" class="img-responsive add-shadow" />
</div>
</div>
Während der Ausführung gibt die Konsole für jeden dekodierten Barcode eine Zeile aus, gefolgt von einer Zusammenfassung mit Dateianzahl, erfolgreichen Lesevorgängen, leeren Lesevorgängen, Fehlern und der verstrichenen Zeit. Fehler werden mit ihren zugehörigen Dateinamen und Fehlergründen aufgelistet.
Der Prozess unterscheidet drei Ergebniskategorien: Erfolg (Barcodes gefunden und dekodiert), leer (Datei gelesen, aber keine Barcodes erkannt) und Fehler (Ausnahme ausgelöst). Diese Unterscheidung ist wichtig, weil leere Lesevorgänge und Fehler unterschiedliche Reaktionen erfordern. Bei leeren Lesevorgängen sind möglicherweise breitere Formateinstellungen erforderlich, während Fehler oft auf Infrastrukturprobleme wie fehlende Dateien, gesperrte Ressourcen oder fehlende native Abhängigkeiten hinweisen.
Die Fehlerliste speichert den Kontext jeder einzelnen Datei, um die Ursachenanalyse zu unterstützen. In einer CI/CD-Pipeline analysieren Sie diese Ausgabe, um Exit-Codes festzulegen (null für völligen Erfolg und ungleich null, wenn `failCount` größer als null ist) oder leiten Sie Fehlerdetails an ein Benachrichtigungssystem weiter.
Für höheren Durchsatz aktivieren Sie die Parallelverarbeitung, indem Sie `Multithreaded` auf `true` setzen und `MaxParallelThreads` anpassen, um den verfügbaren CPU-Kernen zu entsprechen. Pflegen Sie die Isolation pro Datei, indem Sie die parallele Iteration in `Parallel.ForEach` einbetten und eine threadsichere Sammlung für die Fehlerliste verwenden.
---
## Weiterführende Literatur
- [IronBarcode Tutorials: Barcodes lesen](https://ironsoftware.com/csharp/barcode/tutorials/reading-barcodes/) : Vollständige Anleitungen zum Lesevorgang.
- [Vermeidung falsch positiver Ergebnisse](https://ironsoftware.com/csharp/barcode/troubleshooting/false-positives/) : Reduzierung von Phantommesswerten in verrauschten Bildern.
- [Anleitung zur Bildkorrektur](https://ironsoftware.com/csharp/barcode/how-to/image-correction/) : Filter zur Verbesserung der Lesegenauigkeit.
- [Docker-Einrichtungsleitfaden](https://ironsoftware.com/csharp/barcode/get-started/docker-linux/) : Containerisierte Bereitstellung mit korrekten nativen Abhängigkeiten.
- [BarcodeReaderOptions API-Referenz](https://ironsoftware.com/csharp/barcode/object-reference/api/IronBarCode.BarcodeReaderOptions.html) : vollständige Konfigurationsdokumentation.
- [IronBarcode Änderungsübersicht](https://ironsoftware.com/csharp/barcode/product-updates/changelog/) : Versionsspezifische Fehlerbehebungen und Funktionserweiterungen.
[Die Lizenzierungsoptionen können Sie einsehen](https://ironsoftware.com/csharp/barcode/licensing/) , sobald die Pipeline produktionsbereit ist.
Barcode-Verarbeitungssysteme können unbemerkt ausfallen, wobei Null-Ergebnisse oft fälschlicherweise als "kein Barcode vorhanden" interpretiert werden. Ursachen können jedoch beispielsweise beschädigte Dateien, passwortgeschützte PDFs oder Formatabweichungen sein. Durch die Implementierung einer ordnungsgemäßen Protokollierung und einer strukturierten Fehlerbehandlung werden diese Fehler aufgedeckt und umsetzbare Diagnoseinformationen bereitgestellt.
IronBarcode bietet eine typsichere Ausnahme-Hierarchie im IronBarCode.Exceptions-Namespace, eine eingebaute Logging-API und detaillierte BarcodeResult-Eigenschaften. Zu diesen Eigenschaften gehören das erkannte Format, der dekodierte Wert, die Seitenzahl und die Koordinaten für jede erfolgreiche Dekodierung.
Diese Anleitung erklärt, wie man typisierte Ausnahmen abfängt und interpretiert, diagnostischen Kontext von fehlgeschlagenen Lesevorgängen extrahiert, strukturiertes Logging aktiviert und Fehler während Batch-Operationen isoliert.
Schnellstart: Barcode-Fehler behandeln und Diagnose aktivieren
Um Lese-/Schreibaufrufe in try-catch-Blöcke einzuschließen, die auf die typisierten Ausnahmen von IronBarcode abzielen, werden aussagekräftige Fehlermeldungen anstelle stillschweigender Fehler angezeigt.
1Install IronBarcode with NuGet Package Manager
PM > Install-Package BarCode
Install-Package BarCode
2Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.
Schließen Sie Lese-/Schreibaufrufe in try-catch-Blöcke ein, die auf bestimmte Ausnahmetypen abzielen.
Prüfen Sie BarcodeResults nach einem erfolgreichen Lesevorgang auf leere Einträge oder Einträge mit geringer Zuverlässigkeit.
Aktivieren Sie IronSoftware.Logger , um interne Diagnoseausgaben zu erfassen.
Fehler in Stapelverarbeitungen pro Datei mit einer "Fortsetzen bei Fehler"-Logik isolieren
Wie fange ich IronBarcode Ausnahmen ab und interpretiere sie?
Fangen Sie IronBarcode Ausnahmen von den spezifischsten bis zu den allgemeinsten ab. Ordnen Sie die Catch-Blöcke so an, dass zuerst die Ausnahmen behandelt werden, die zu Aktionen führen, wie z. B. Datei-, PDF-Passwort- und Kodierungsfehler, gefolgt vom Basistyp. Der IronBarCode.Exceptions-Namespace definiert 11 Ausnahmetypen, die jeweils einem bestimmten Fehlermodus entsprechen:
IronBarcode Ausnahmetypen – Ursachen und empfohlene Lösungen
Ausnahmetyp
Auslösen
Empfohlene Lösung
IronBarCodeFileException
Die Datei ist beschädigt, gesperrt oder liegt in einem nicht unterstützten Bildformat vor.
Prüfen Sie, ob die Datei ein unterstütztes Bildformat aufweist und nicht gesperrt ist; fangen Sie außerdem FileNotFoundException für fehlende Dateien separat ab.
IronBarCodePdfPasswordException
Die PDF-Datei ist passwortgeschützt oder verschlüsselt.
Geben Sie das Passwort über PdfBarcodeReaderOptions an oder überspringen Sie die Datei und das Protokoll.
IronBarCodeEncodingException
Fehler bei der allgemeinen Codierung während der Barcode-Generierung
Überprüfen, ob die Eingabedaten den Zielvorgaben BarcodeWriterEncoding entsprechen.
IronBarCodeContentTooLongEncodingException
Der Wert überschreitet die Zeichenbegrenzung für die ausgewählte Symbolisierung.
Daten kürzen oder auf ein Format mit höherer Kapazität (QR, DataMatrix) umstellen
Nicht-numerische Zeichen werden in ein rein numerisches Format (EAN, UPC) umgewandelt.
Eingabe bereinigen oder auf ein alphanumerisches Format umstellen (Code128, Code39).
IronBarCodeUnsupportedRendererEncodingException
Die ausgewählte BarcodeEncoding kann von IronBarcode nicht beschrieben werden.
Verwenden Sie die Enumeration BarcodeWriterEncoding anstelle von BarcodeEncoding
IronBarCodeParsingException
Strukturierte Daten (GS1-128) können während der Analyse nicht validiert werden.
Die GS1-Struktur sollte vor dem Parsen mit Code128GS1Parser.IsValid() validiert werden.
IronBarCodeNativeException
Fehler in der nativen Interop-Schicht (fehlende DLLs, Plattforminkompatibilität)
Prüfen Sie, ob die plattformspezifischen NuGet Pakete installiert sind (BarCode.Linux, BarCode.macOS).
IronBarCodeConfidenceThresholdException
Ungültiges Argument für den Konfidenzschwellenwert an die Leseroptionen übergeben
Stellen Sie sicher, dass ConfidenceThreshold zwischen 0,0 und 1,0 liegt.
IronBarCodeUnsupportedException
Dieser Vorgang wird im aktuellen Kontext nicht unterstützt.
Prüfen Sie im Änderungsprotokoll , ob die Funktionen in Ihrer Version verfügbar sind.
IronBarCodeException
Basistyp – fängt alle IronBarcode-spezifischen Fehler ab, die oben nicht abgeglichen wurden
Protokollieren Sie alle Ausnahmedetails und eskalieren Sie diese zur Untersuchung.
Verwenden Sie Ausnahmefilter mit when-Klauseln, um überlappende Ausnahmetypen ohne tiefes Schachteln zu leiten. Fehlende Dateien werfen den Standard-System.IO.FileNotFoundException anstelle von IronBarCodeFileException, daher fügen Sie einen separaten catch-Block für diesen Fall hinzu:
Eingabe
Ein Code128-Barcode, der eine Rechnungsnummer kodiert (Erfolgspfad), und ein Lageretiketten-Barcode, der den Inhalt der fehlenden PDF-Datei darstellt (Fehlerpfad).
scanner-invoice.png (Erfolgspfad)
warehouse-labels.pdf (Fehlerpfad – Datei nicht auf der Festplatte vorhanden)
using IronBarCode;using IronBarCode.Exceptions;// Success path: valid file present on diskstring 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 foundConsole.WriteLine($"[{result.BarcodeType}] {result.Value}"); }}catch (IronBarCodePdfPasswordException ex){ // PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retryingConsole.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");}catch (IronBarCodeFileException ex){ // File is present but corrupted, locked, or in an unsupported formatConsole.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");}catch (FileNotFoundException ex){ // Missing files throw FileNotFoundException, not IronBarCodeFileExceptionConsole.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 belowConsole.Error.WriteLine($"Missing native dependency: {ex.Message}");}catch (IronBarCodeException ex){ // Base catch for any IronBarcode-specific error not matched by the blocks aboveConsole.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");}
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}");
}
ImportsIronBarCodeImportsIronBarCode.Exceptions' Success path: valid file present on diskDim filePath AsString = "scanned-invoice.png"' Failure path: file does not exist → caught by FileNotFoundException below' Dim filePath As String = "warehouse-labels.pdf"Try Dim results AsBarcodeResults = BarcodeReader.Read(filePath) For Each result AsBarcodeResultIn results ' Print the detected symbology and decoded value for each barcode foundConsole.WriteLine($"[{result.BarcodeType}] {result.Value}") NextCatch ex AsIronBarCodePdfPasswordException ' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retryingConsole.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")Catch ex AsIronBarCodeFileException ' File is present but corrupted, locked, or in an unsupported formatConsole.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")Catch ex AsFileNotFoundException ' Missing files throw FileNotFoundException, not IronBarCodeFileExceptionConsole.Error.WriteLine($"File not found: {filePath} — {ex.Message}")Catch ex AsIronBarCodeNativeExceptionWhen ex.Message.Contains("DLL") ' The when filter routes only missing-DLL errors here; other native exceptions ' fall through to the IronBarCodeException block belowConsole.Error.WriteLine($"Missing native dependency: {ex.Message}")Catch ex AsIronBarCodeException ' Base catch for any IronBarcode-specific error not matched by the blocks aboveConsole.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")EndTry
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
Ausgabe
Hinweis:: Eine gültige Datei wird zum dekodierten Barcode-Typ und -Wert aufgelöst.
Eine fehlende Datei löst FileNotFoundException aus, das durch den dedizierten catch-Block geleitet wird.
Der when (ex.Message.Contains("DLL"))-Filter auf IronBarCodeNativeException leitet fehlende Abhängigkeitsfehler an einen speziellen Handler, ohne andere native Ausnahmen zu beeinflussen. Dieser Ansatz ist besonders nützlich bei Docker-Bereitstellungen, bei denen plattformspezifische Pakete fehlen könnten.
IronSoftware.Exceptions.LicensingException wird separat geworfen, wenn der Lizenzschlüssel ungültig oder fehlend ist. Fangen Sie diese Ausnahme beim Start der Anwendung ab, anstatt bei einzelnen Lese- oder Schreibaufrufen.
Wie extrahiere ich Diagnosedetails aus fehlgeschlagenen Lesevorgängen?
Ein Lesevorgang, der kein Ergebnis liefert, stellt keine Ausnahme dar; es erzeugt eine leere BarcodeResults-Sammlung. Der Diagnosekontext wird durch die Prüfung der Eingabeparameter, der konfigurierten Optionen und etwaiger zurückgegebener Teilergebnisse ermittelt.
Das BarcodeResult-Objekt bietet Eigenschaften, die nützlich für die nachträgliche Analyse sind, einschließlich BarcodeType, Value, PageNumber und Points (Eckkoordinaten). Wenn Ergebnisse vorhanden, aber unerwartet sind, überprüfen Sie zuerst BarcodeType gegen das erwartete Format und verifizieren Sie PageNumber.
Eingabe
Ein Code128-Barcode, der eine Rechnungsnummer kodiert, wird mit ExpectBarcodeTypes auf Code128 gesetzt und QRCode sowie ReadingSpeed.Detailed für gründliches Scannen gelesen.
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 accuracyvar options = new BarcodeReaderOptions{ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formatsSpeed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged imagesExpectMultipleBarcodes = 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 optionsif (results == null || results.Count == 0){ // Log the configured options alongside the warning so the cause is immediately actionableConsole.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})"); }}
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})");
}
}
ImportsIronBarCodeDim filePath AsString = "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 accuracyDim options As New BarcodeReaderOptionsWith { .ExpectBarcodeTypes = BarcodeEncoding.Code128OrBarcodeEncoding.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 AsBarcodeResults = BarcodeReader.Read(filePath, options)' An empty result is not an exception — it means no barcode matched the configured optionsIf results Is NothingOrElse results.Count = 0 Then ' Log the configured options alongside the warning so the cause is immediately actionableConsole.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 AsBarcodeResultIn results ' Points contains the four corner coordinates of the barcode in the image; ' use the first corner as a representative position indicator Dim pos AsString = 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})") NextEnd If
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
Ausgabe
Hinweis:: Wenn ExpectBarcodeTypes mit dem Barcode im Bild übereinstimmt, gibt das Lesen den Typ, den Wert, die Seitennummer und die Position zurück.
Wenn ExpectBarcodeTypes die tatsächliche Symbologie nicht enthält, gibt das Lesen ein leeres Ergebnis zurück. Der [WARN]-Block protokolliert die konfigurierten Typen, die Lesegeschwindigkeit und eine vorgeschlagene nächste Aktion.
Bei der Diagnostik lassen sich zwei häufige Muster erkennen. Leere Ergebnisse mit einer engen ExpectBarcodeTypes-Einstellung bedeuten oft, dass der Barcode eine andere Symbologie verwendet; die Erweiterung auf BarcodeEncoding.All kann dies bestätigen. Unerwartete Dekodierungsergebnisse deuten in der Regel auf eine schlechte Bildqualität hin.
Das Anwenden von Bildfiltern und ein erneuter Versuch mit einer langsameren Lesegeschwindigkeit beheben diese Probleme oft. Sie können auch die RemoveFalsePositive-Option umschalten, um Phantomlesungen von unruhigen Hintergründen zu eliminieren.
Wie aktiviere ich die ausführliche Protokollierung für Barcode-Operationen?
IronBarcode bietet eine eingebaute Logging-API über IronSoftware.Logger. Legen Sie vor jeglichen Barcode-Operationen den Protokollierungsmodus und den Dateipfad fest, um interne Diagnoseausgaben aus den Lese- und Schreibpipelines zu erfassen.
Eingabe
Als Leseziel wird ein Code128-Barcode-TIFF-Bild verwendet, während die ausführliche Protokollierung aktiviert ist.
using IronBarCode;// Enable IronBarcode's built-in logging — set BEFORE any read/write calls// LoggingModes.All writes both debug output and file-level diagnosticsIronSoftware.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 callsvar 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.");
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.");
ImportsIronBarCode' Enable IronBarcode's built-in logging — set BEFORE any read/write calls' LoggingModes.All writes both debug output and file-level diagnosticsIronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.AllIronSoftware.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 callsDim options As New BarcodeReaderOptionsWith { .Speed = ReadingSpeed.Detailed, .ExpectBarcodeTypes = BarcodeEncoding.All' scan for every supported symbology}Dim results AsBarcodeResults = 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 erfasst sowohl Debug-Ausgaben als auch logging auf Dateiebene. Die Protokolldatei zeichnet interne Verarbeitungsschritte auf, wie z. B. Vorverarbeitungsphasen von Bildern, Versuche zur Formaterkennung und native Interop-Aufrufe, die über die öffentliche API nicht sichtbar sind.
Für Produktionspipelines mit einem strukturierten Logging-Framework (Serilog, NLog, Microsoft.Extensions.Logging) fügt das Einbinden von IronBarcode-Operationen in eine Middleware-Schicht strukturierte JSON-Einträge neben der eingebauten Protokolldatei hinzu. Der eingebaute Logger schreibt Diagnosen im Klartext, die für die Unterstützungseskalation nützlich sind; Der strukturierte Wrapper stellt abfragbare Felder für den Observability-Stack bereit.
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.BarcodeResultsReadWithDiagnostics(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 CloudWatchConsole.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 timeConsole.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 }}
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
}
}
ImportsIronBarCodeImportsSystem.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.FunctionReadWithDiagnostics(filePath AsString, options AsBarcodeReaderOptions) AsBarcodeResults Dim sw AsStopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is includedTry Dim results AsBarcodeResults = BarcodeReader.Read(filePath, options) sw.Stop() ' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatchConsole.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}") Return resultsCatch ex AsException sw.Stop() ' Emit a structured error entry to stderr with exception type, message, and elapsed timeConsole.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 normallyEndTryEnd Function
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
Die strukturierte Ausgabe lässt sich direkt in Log-Aggregationswerkzeuge integrieren. Leiten Sie stdout in einer containerisierten Bereitstellung an Fluentd, Datadog oder CloudWatch weiter. Das Feld "Verstrichene Zeit" hebt Leistungseinbußen hervor, bevor diese zu SLA-Verletzungen führen.
Ausgabe
Wie kann ich die Stapelverarbeitung von Barcodes debuggen?
Mehrere Dateien werden verarbeitet, indem jeder Lesevorgang in einem eigenen try-catch-Block isoliert wird, die Ergebnisse für jede Datei werden aufgezeichnet und eine zusammenfassende Gesamtfassung erstellt. Die Pipeline wird trotz Ausfällen fortgesetzt, anstatt beim ersten Fehler anzuhalten.
Eingabe
Vier der fünf Code128-Barcode-Bilder aus dem scans/-Batch-Verzeichnis. Die fünfte Datei (scan-05-broken.png) enthält ungültige Bytes, um eine Dateiausnahme auszulösen.
Charge 1 - Scan 1
Stapel 1 - Scan 2
Stapel 1 - Scan 3
Stapel 1 - Scan 4
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 outputIronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;IronSoftware.Logger.LogFilePath = "batch-run.log";// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectoriesstring[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);var options = new BarcodeReaderOptions{Speed = ReadingSpeed.Balanced, // balances throughput vs accuracyExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formatsExpectMultipleBarcodes = 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<(stringFile, stringError)>(); // per-file error context for root cause analysisvar 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 codeConsole.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}"); }}
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}");
}
}
ImportsIronBarCodeImportsIronBarCode.ExceptionsImportsSystem.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 outputIronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.AllIronSoftware.Logger.LogFilePath = "batch-run.log"' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectoriesDim files AsString() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)Dim options As New BarcodeReaderOptionsWith { .Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy .ExpectBarcodeTypes = BarcodeEncoding.Code128OrBarcodeEncoding.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 AsInteger = 0Dim failCount AsInteger = 0Dim emptyCount AsInteger = 0Dim errors As New List(Of (FileAsString, ErrorAsString))() ' per-file error context for root cause analysisDim sw AsStopwatch = Stopwatch.StartNew()For Each file AsStringIn filesTry Dim results AsBarcodeResults = BarcodeReader.Read(file, options) ' Empty result is not an exception — the file was read but contained no matching barcode If results Is NothingOrElse 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 AsBarcodeResultIn resultsConsole.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}") Next successCount += 1Catch ex AsIronBarCodePdfPasswordException ' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover failCount += 1 errors.Add((file, "Password-protected PDF"))Catch ex AsIronBarCodeFileException ' File is corrupted, locked, or in an unsupported image format failCount += 1 errors.Add((file, $"File error: {ex.Message}"))Catch ex AsFileNotFoundException ' 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 AsIronBarCodeException ' Catch-all for any other IronBarcode-specific errors not handled above failCount += 1 errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))Catch ex AsException ' Unexpected non-IronBarcode error — log the full type for investigation failCount += 1 errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))EndTryNextsw.Stop()' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit codeConsole.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() ThenConsole.WriteLine(vbCrLf & "--- Error Details ---") For Each errorDetail In errorsConsole.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}") NextEnd If
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
Ausgabe
Während der Ausführung gibt die Konsole für jeden dekodierten Barcode eine Zeile aus, gefolgt von einer Zusammenfassung mit Dateianzahl, erfolgreichen Lesevorgängen, leeren Lesevorgängen, Fehlern und der verstrichenen Zeit. Fehler werden mit ihren zugehörigen Dateinamen und Fehlergründen aufgelistet.
Der Prozess unterscheidet drei Ergebniskategorien: Erfolg (Barcodes gefunden und dekodiert), leer (Datei gelesen, aber keine Barcodes erkannt) und Fehler (Ausnahme ausgelöst). Diese Unterscheidung ist wichtig, weil leere Lesevorgänge und Fehler unterschiedliche Reaktionen erfordern. Bei leeren Lesevorgängen sind möglicherweise breitere Formateinstellungen erforderlich, während Fehler oft auf Infrastrukturprobleme wie fehlende Dateien, gesperrte Ressourcen oder fehlende native Abhängigkeiten hinweisen.
Die Fehlerliste speichert den Kontext jeder einzelnen Datei, um die Ursachenanalyse zu unterstützen. In einer CI/CD-Pipeline analysieren Sie diese Ausgabe, um Exit-Codes festzulegen (null für völligen Erfolg und ungleich null, wenn failCount größer als null ist) oder leiten Sie Fehlerdetails an ein Benachrichtigungssystem weiter.
Für höheren Durchsatz aktivieren Sie die Parallelverarbeitung, indem Sie Multithreaded auf true setzen und MaxParallelThreads anpassen, um den verfügbaren CPU-Kernen zu entsprechen. Pflegen Sie die Isolation pro Datei, indem Sie die parallele Iteration in Parallel.ForEach einbetten und eine threadsichere Sammlung für die Fehlerliste verwenden.
Wie kann ich Fehler bei Barcode-Operationen mit IronBarcode behandeln?
IronBarcode bietet typisierte Ausnahmen und eine integrierte Protokollierung, um Fehler bei Barcode-Operationen effizient zu verwalten und zu behandeln und so einen reibungslosen Ablauf Ihrer Anwendung zu gewährleisten.
Welche Funktionen bietet IronBarcode zur Behebung von Barcode-Problemen?
IronBarcode beinhaltet die Extraktion von Diagnosedaten und die produktionsreife Fehlerisolierung für Batchverarbeitung, wodurch Entwickler bei der effizienten Identifizierung und Behebung von Barcode-bezogenen Problemen unterstützt werden.
Kann IronBarcode Fehler während der Barcode-Verarbeitung protokollieren?
Ja, IronBarcode verfügt über integrierte Protokollierungsfunktionen, die es Entwicklern ermöglichen, Fehlerdetails während der Barcode-Verarbeitung zu erfassen und zu protokollieren, was die Fehlersuche erleichtert.
Was sind typisierte Ausnahmen in IronBarcode?
Typisierte Ausnahmen in IronBarcode sind spezifische Fehlertypen, die detaillierte Informationen über Probleme bei der Barcode-Funktion liefern und es Entwicklern erleichtern, Probleme zu diagnostizieren und zu beheben.
Wie unterstützt IronBarcode die Fehlerisolierung bei Stapelverarbeitung?
IronBarcode bietet eine produktionsreife Fehlerisolierung für Batchverarbeitung, die dabei hilft, fehlerhafte Barcode-Operationen von erfolgreichen zu trennen und so das Fehlermanagement bei der Batchverarbeitung zu optimieren.
Gibt es eine Möglichkeit, Diagnosedaten aus Barcode-Operationen mit IronBarcode zu extrahieren?
Ja, IronBarcode bietet Diagnose-Extraktionswerkzeuge, die Entwicklern helfen, detaillierte Informationen über Barcode-Operationen zu sammeln und so die Fehlersuche und -behebung zu erleichtern.
How can I catch and interpret exceptions effectively in IronBarcode?
Catch and interpret exceptions in IronBarcode by ordering your try-catch blocks from specific to general. Start with actionable exceptions like file errors or PDF password issues and end with the base IronBarCodeException to ensure comprehensive error handling.
What properties of BarcodeResult can be used for post-mortem analysis?
The BarcodeResult object in IronBarcode provides properties like BarcodeType, Value, PageNumber, and Points (coordinates) for post-mortem analysis. These properties help in understanding unexpected results by checking the actual versus expected barcode type and verifying the page number.
In IronBarcode, how can I prevent false positives during barcode reads?
To prevent false positives during barcode reads in IronBarcode, you can use image filters to enhance image quality and the RemoveFalsePositive option. Additionally, adjusting reading speed and ExpectBarcodeTypes can minimize errors from noisy backgrounds.
How does IronBarcode handle errors from encrypted PDFs?
IronBarcode handles errors from encrypted PDFs using the IronBarCodePdfPasswordException. To process such files, supply the password using PdfBarcodeReaderOptions or log and skip them for non-disruptive barcode processing.
Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender Handbücher.