Wie man Nullprüfungen für Barcode-Operationen in C# handhabt
IronBarcode gibt Scan-Ergebnisse als BarcodeResults Sammlung in C# bis BarcodeReader.Read zurück. Diese Methode gibt null zurück, wenn das Eingabebild nicht erkannt wird, oder eine leere Sammlung, wenn keine Barcodes erkannt werden. BarcodeWriter.CreateBarcode löst eine Ausnahme aus, wenn die Eingabe null, leer oder in einem ungültigen Format ist.
Scanquellen aus der Praxis, wie z. B. Kamerabilder, Dokumenten-Uploads und Lagerscanner, liefern möglicherweise nicht immer einen lesbaren Barcode. Der Zugriff auf Ergebniseigenschaften oder das Durchlaufen der Auflistung ohne Prüfung auf Null- oder leere Werte kann zur Laufzeit einen NullReferenceException-Fehler verursachen. Die Übergabe ungültiger Zeichenketten an die Schreib-API kann eine ArgumentException auslösen. Die Verwendung von Schutzklauseln sowohl bei Lese- als auch bei Schreibvorgängen hilft, diese Ausnahmen im Produktivbetrieb zu vermeiden.
Diese Anleitung erklärt, wie man Null- und leere Ergebnisse bei IronBarcode -Lese- und Schreibvorgängen mithilfe von Guard-Klauseln, Konfidenzfiltern und einem wiederverwendbaren Validierungsmuster behandelt.
Schnellstart: Umgang mit Null-Ergebnissen bei Barcode-Operationen
Verwenden Sie das Guard-Pattern von IronBarcode, um die Sammlung BarcodeResults sicher zu überprüfen, bevor Sie auf Ergebniseigenschaften zugreifen. Legen Sie sofort los mit dieser kurzen Lektüre und Überprüfung:
-
Installieren Sie IronBarcode mit NuGet Package Manager
PM > Install-Package BarCode -
Kopieren Sie diesen Codeausschnitt und führen Sie ihn aus.
using IronBarCode; BarcodeResults results = BarcodeReader.Read("label.png"); // Guard: null or empty if (results is null || results.Count == 0) { Console.WriteLine("No barcodes detected."); return; } Console.WriteLine(results.First().Value); -
Bereitstellen zum Testen in Ihrer Live-Umgebung
Beginnen Sie noch heute, IronBarcode in Ihrem Projekt zu verwenden, mit einer kostenlosen Testversion
Wie man die Nullwertprüfung für Barcode-Operationen mit IronBarcode handhabt
- Laden Sie die IronBarcode Bibliothek von NuGet herunter.
- Rufen Sie
BarcodeReader.Readauf und erfassen Sie den RückgabewertBarcodeResults - Prüfen Sie vor dem Zugriff auf Ergebnisse, ob diese null sind.
- Überprüfen Sie die einzelnen Eigenschaften
BarcodeResultvor der weiteren Verwendung. - Legen Sie
ConfidenceThresholdinBarcodeReaderOptionsfest, um minderwertige Lesevorgänge auf Scan-Ebene zu filtern.
Wie geht man mit Null- und leeren Barcode-Ergebnissen um?
Es gibt zwei Fehlermodi: BarcodeResults ist null, wenn die Eingabe kein gültiges Bild ist, und leer, wenn das Bild keine Barcodes enthält. Der Zugriff auf First, Value oder das Durchlaufen der Liste ohne vorherige Überprüfung beider Bedingungen führt zu einer Laufzeitausnahme.
Prüfen Sie beide Bedingungen, bevor Sie in die Verarbeitungsschleife eintreten:
Eingabe
Ein Versandetikett mit Code128-Barcode (Erfolgsfall) und ein leeres Bild ohne Barcode (Fehlerfall).
shipping-label.png (Erfolgspfad)
blank-image.png (Fehlerpfad, kein Barcode vorhanden)
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-guard.cs
using IronBarCode;
// BarcodeReader.Read() returns a BarcodeResults collection, not a single result
BarcodeResults results = BarcodeReader.Read("shipping-label.png");
// Null check: image was not recognized as a valid image source
// Empty check: image was valid but contained no detectable barcodes
if (results is null || results.Count == 0)
{
// Log, return a default, or throw a domain-specific exception
Console.WriteLine("No barcodes found in the input image.");
return;
}
// Collection is safe to iterate; each BarcodeResult holds one decoded barcode
foreach (BarcodeResult result in results)
{
// Guard individual result properties; partial scans or severely
// damaged barcodes can produce results where .Value is empty or whitespace
if (string.IsNullOrWhiteSpace(result.Value))
{
Console.WriteLine($"Empty value detected for {result.BarcodeType}");
continue;
}
// BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
Imports IronBarCode
' BarcodeReader.Read() returns a BarcodeResults collection, not a single result
Dim results As BarcodeResults = BarcodeReader.Read("shipping-label.png")
' Null check: image was not recognized as a valid image source
' Empty check: image was valid but contained no detectable barcodes
If results Is Nothing OrElse results.Count = 0 Then
' Log, return a default, or throw a domain-specific exception
Console.WriteLine("No barcodes found in the input image.")
Return
End If
' Collection is safe to iterate; each BarcodeResult holds one decoded barcode
For Each result As BarcodeResult In results
' Guard individual result properties; partial scans or severely
' damaged barcodes can produce results where .Value is empty or whitespace
If String.IsNullOrWhiteSpace(result.Value) Then
Console.WriteLine($"Empty value detected for {result.BarcodeType}")
Continue For
End If
' BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
Jeder BarcodeResult stellt die String-Eigenschaften Value und Text bereit, die beide den dekodierten Barcode-Inhalt zurückgeben. Stark beschädigte Barcodes oder unvollständige Scans können zu leeren oder weißen Werten führen. Verwenden Sie string.IsNullOrWhiteSpace für jedes Ergebnis, um zu verhindern, dass leere Werte nachgelagerte Systeme erreichen.
BarcodeReaderOptions verfügt außerdem über eine ConfidenceThreshold Eigenschaft (0,0 bis 1,0), die minderwertige Lesevorgänge verwirft, bevor sie die Ergebnissammlung erreichen:
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/confidence-filter.cs
using IronBarCode;
// ConfidenceThreshold filters low-quality reads before they enter the
// BarcodeResults collection. Reads below the threshold are discarded
// during scanning, not after, so no post-filtering of the collection is needed.
var options = new BarcodeReaderOptions
{
ConfidenceThreshold = 0.7 // range 0.0 to 1.0; lower values accept weaker signals
};
BarcodeResults results = BarcodeReader.Read("shipping-label.png", options);
// Still check for null and empty even with a threshold applied;
// an image with no barcodes returns an empty collection, not null
if (results is null || results.Count == 0)
{
Console.WriteLine("No barcodes met the confidence threshold.");
return;
}
foreach (var result in results)
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
Imports IronBarCode
' ConfidenceThreshold filters low-quality reads before they enter the
' BarcodeResults collection. Reads below the threshold are discarded
' during scanning, not after, so no post-filtering of the collection is needed.
Dim options As New BarcodeReaderOptions With {
.ConfidenceThreshold = 0.7 ' range 0.0 to 1.0; lower values accept weaker signals
}
Dim results As BarcodeResults = BarcodeReader.Read("shipping-label.png", options)
' Still check for null and empty even with a threshold applied;
' an image with no barcodes returns an empty collection, not null
If results Is Nothing OrElse results.Count = 0 Then
Console.WriteLine("No barcodes met the confidence threshold.")
Return
End If
For Each result In results
Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
Wie wendet man Null-sichere Muster beim Barcode-Schreiben an?
BarcodeWriter.CreateBarcode nimmt einen String-Wert und einen BarcodeWriterEncoding oder BarcodeEncoding Enum-Wert entgegen. Das Übergeben eines Nullwerts oder einer leeren Zeichenkette führt sofort zu einer Ausnahme. Es gelten auch Formatbeschränkungen: EAN-8 akzeptiert 7 bis 8 Ziffern, UPC-A akzeptiert 11 bis 12 und Code 128 hat eine Zeichenbegrenzung. Durch die Validierung der Eingabe vor dem Aufruf werden diese Ausnahmen vom Kodierungsschritt ferngehalten:
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-safe-write.cs
using IronBarCode;
// Input may arrive from user input, a database, or an API response
string inputValue = GetValueFromUserOrDatabase(); // Could be null
// Guard: null, empty, or whitespace input cannot produce a valid barcode
if (string.IsNullOrWhiteSpace(inputValue))
{
Console.WriteLine("Cannot generate barcode: input value is null or empty.");
return;
}
// Guard: format-specific constraints must be satisfied before encoding
// EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
BarcodeWriterEncoding encoding = BarcodeWriterEncoding.EAN8;
if (encoding == BarcodeWriterEncoding.EAN8 && !System.Text.RegularExpressions.Regex.IsMatch(inputValue, @"^\d{7,8}$"))
{
Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.");
return;
}
// Input is validated; CreateBarcode will not throw for null or format mismatch
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
Imports IronBarCode
' Input may arrive from user input, a database, or an API response
Dim inputValue As String = GetValueFromUserOrDatabase() ' Could be Nothing
' Guard: null, empty, or whitespace input cannot produce a valid barcode
If String.IsNullOrWhiteSpace(inputValue) Then
Console.WriteLine("Cannot generate barcode: input value is null or empty.")
Return
End If
' Guard: format-specific constraints must be satisfied before encoding
' EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
Dim encoding As BarcodeWriterEncoding = BarcodeWriterEncoding.EAN8
If encoding = BarcodeWriterEncoding.EAN8 AndAlso Not System.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") Then
Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.")
Return
End If
' Input is validated; CreateBarcode will not throw for null or format mismatch
Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode(inputValue, encoding)
barcode.SaveAsPng("output-barcode.png")
Ausgabe
Eine gültige 7-stellige Eingabe (1234567) erzeugt einen scannbaren EAN-8-Barcode. Nullwerte, leere oder nicht-numerische Eingaben werden von den Schutzklauseln abgefangen und erreichen niemals den Kodierungsschritt.
Die Schreib-API führt auch eine eigene interne Validierung durch: Sie prüft Prüfsummen, verifiziert Längenbeschränkungen und weist ungültige Zeichen für die ausgewählte Kodierung zurück. Die oben genannten Schutzklauseln fangen Probleme früher ab und geben dem Aufrufer die Kontrolle über die Fehlermeldung und den Wiederherstellungspfad. Eine vollständige Liste der unterstützten Kodierungen und ihrer Einschränkungen finden Sie in der Anleitung zur Barcode-Erstellung und im Leitfaden zum Erstellen von Barcodes aus Daten .
Wie lassen sich Ergebnisse vor der Weiterverarbeitung validieren?
Wenn Barcode-Daten in ein anderes System eingespeist werden (z. B. Datenbankeinträge, API-Aufrufe, Etikettendrucker), ist es hilfreich, die Ergebnisanzahl, die Datenintegrität und die Typüberprüfungen in einer einzigen wiederverwendbaren Methode zusammenzufassen, bevor die Daten weitergegeben werden:
Eingabe
Ein Code128-Barcode-Lagerscan, der als Leseziel für den Validator verwendet wird.
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/barcode-validator.cs
using IronBarCode;
using System.Collections.Generic;
using System.Linq;
// Reusable validation helper — consolidates null, empty, value, and
// expected-format checks into a single method. Returns an empty list
// (never null) so callers do not need to null-check the return value.
public static class BarcodeValidator
{
public static List<BarcodeResult> GetValidResults(
string imagePath,
BarcodeEncoding? expectedType = null,
double confidenceThreshold = 0.7)
{
// Apply confidence threshold at scan level via BarcodeReaderOptions
var options = new BarcodeReaderOptions
{
ConfidenceThreshold = confidenceThreshold
};
BarcodeResults results = BarcodeReader.Read(imagePath, options);
// Return empty list instead of null so callers never need to null-check the return value
if (results is null || results.Count == 0)
return new List<BarcodeResult>();
return results
.Where(r => !string.IsNullOrWhiteSpace(r.Value)) // skip results with empty decoded data
.Where(r => expectedType == null || r.BarcodeType == expectedType) // null accepts any symbology
.ToList();
}
}
// Usage: pass the image path and the symbology you expect
var validated = BarcodeValidator.GetValidResults(
"warehouse-scan.png",
expectedType: BarcodeEncoding.Code128,
confidenceThreshold: 0.7);
if (validated.Count == 0)
{
// No valid results; log the failure and skip downstream processing
return;
}
// All results have passed null, empty, type, and confidence checks
foreach (var barcode in validated)
{
SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call
}
Imports IronBarCode
Imports System.Collections.Generic
Imports System.Linq
' Reusable validation helper — consolidates null, empty, value, and
' expected-format checks into a single method. Returns an empty list
' (never null) so callers do not need to null-check the return value.
Public Module BarcodeValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedType As BarcodeEncoding? = Nothing,
Optional confidenceThreshold As Double = 0.7) As List(Of BarcodeResult)
' Apply confidence threshold at scan level via BarcodeReaderOptions
Dim options As New BarcodeReaderOptions With {
.ConfidenceThreshold = confidenceThreshold
}
Dim results As BarcodeResults = BarcodeReader.Read(imagePath, options)
' Return empty list instead of null so callers never need to null-check the return value
If results Is Nothing OrElse results.Count = 0 Then
Return New List(Of BarcodeResult)()
End If
Return results _
.Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)) _ ' skip results with empty decoded data
.Where(Function(r) expectedType Is Nothing OrElse r.BarcodeType = expectedType) _ ' null accepts any symbology
.ToList()
End Function
End Module
' Usage: pass the image path and the symbology you expect
Dim validated = BarcodeValidator.GetValidResults(
"warehouse-scan.png",
expectedType:=BarcodeEncoding.Code128,
confidenceThreshold:=0.7)
If validated.Count = 0 Then
' No valid results; log the failure and skip downstream processing
Return
End If
' All results have passed null, empty, type, and confidence checks
For Each barcode In validated
SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream call
Next barcode
Die Methode gibt eine leere Liste anstelle von null zurück, sodass Aufrufer den Rückgabewert nie auf null prüfen müssen. Der optionale Parameter expectedType filtert nach Symbologie, wodurch verhindert wird, dass das nachgelagerte System unerwartete Formate empfängt, wenn ein Scan sowohl einen QR-Code als auch einen Code 128 aus demselben Bild erfasst.
Beim Stapellesen mehrerer Dateien wird für jede Datei dasselbe Muster angewendet und die Ergebnisse werden anschließend aggregiert. Die Option ExpectBarcodeTypes auf BarcodeReaderOptions beschränkt den Scan von vornherein auf erwartete Symbologien, sodass weniger unerwünschte Ergebnisse den Validator erreichen.
Weiterführende Literatur
- Tutorial zum Lesen von Barcodes : Scan-Konfiguration und Leseoptionen.
- Leitfaden zu Ausgabedatenformaten : alle
BarcodeResultEigenschaften und ihre Typen. - Barcode aus Daten erstellen : Codierungsbeschränkungen für jede Symbologie.
- BarcodeReaderOptions API-Referenz : vollständige Konfigurationsdokumentation.
- IronBarcode Änderungsübersicht : Versionsspezifische Fehlerbehebungen und Funktionserweiterungen.
Die Lizenzierungsoptionen können Sie einsehen , sobald die Pipeline produktionsbereit ist.
Häufig gestellte Fragen
Was versteht man unter Nullwertprüfung bei Barcode-Operationen?
Die Nullprüfung bei Barcode-Operationen beinhaltet die Überprüfung, ob ein Barcode-Ergebnis oder eine Eingabe null ist, um Laufzeitfehler zu vermeiden und eine reibungslose Barcode-Verarbeitung zu gewährleisten.
Warum ist die Nullprüfung bei Barcode-Operationen in C# wichtig?
Die Überprüfung auf Nullwerte ist bei Barcode-Operationen in C# von entscheidender Bedeutung, um Ausnahmen zu vermeiden und sicherzustellen, dass die Anwendung Fälle, in denen Barcode-Daten fehlen oder ungültig sind, problemlos behandeln kann.
Wie kann IronBarcode bei der Nullwertprüfung helfen?
IronBarcode bietet integrierte Methoden zur einfachen Behandlung von Null-Prüfungen, sodass Entwickler Barcode-Daten sicher verwalten können, ohne komplexe Validierungslogik manuell implementieren zu müssen.
Welche Best Practices gibt es für die Nullwertprüfung in IronBarcode?
Zu den bewährten Verfahren gehören die Überprüfung von BarcodeResults auf Nullwerte, die Validierung der Eingaben vor der Verarbeitung und die Verwendung von Konfidenzfiltern, um zuverlässige Ergebnisse beim Barcode-Scannen zu gewährleisten.
Kann IronBarcode die Ergebnisse nach Konfidenzintervall filtern, um Null-Ausgaben zu vermeiden?
Ja, IronBarcode ermöglicht das Filtern von Barcode-Ergebnissen nach Konfidenzniveaus, was dazu beiträgt, Null-Ausgaben zu reduzieren und eine hohe Genauigkeit beim Barcode-Lesen zu gewährleisten.
Gibt es eine Möglichkeit, Schreibeingaben mit IronBarcode zu validieren?
IronBarcode ermöglicht die Validierung von Schreibeingaben, um sicherzustellen, dass die in Barcodes kodierten Daten korrekt und vollständig sind und Probleme bei der Barcode-Generierung vermieden werden.
Was passiert, wenn ein Null-Barcode-Ergebnis nicht behandelt wird?
Wird ein Null-Barcode-Ergebnis nicht behandelt, kann dies zu Laufzeitausnahmen führen und den Ablauf der Anwendung stören, was potenziell zu Abstürzen oder fehlerhaften Operationen führen kann.

