如何在 C# 中處理 BarCode 操作的空值檢查

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

IronBarcode 透過 BarcodeReader.Read,將掃描結果以 BarcodeResults 集合的形式回傳至 C#。 若輸入的圖片無法被識別,此方法將返回 null;若未偵測到 BARCODE,則返回一個空集合。 BarcodeWriter.CreateBarcode 若輸入為 null、空值或格式不正確,則會拋出例外。

實際的掃描來源(例如攝影機畫面、文件上傳及倉儲掃描器)未必總能提供可讀取的BARCODE。 若在存取結果屬性或迭代集合時未檢查 null 或空值,可能會在執行時引發 NullReferenceException 錯誤。若將無效字串傳遞給寫入 API,可能會導致 ArgumentException 錯誤。 在讀取與寫入操作中使用防護子句,有助於在生產環境中防止這些例外發生。

本操作指南說明如何透過守護子句、可信度篩選以及可重複使用的驗證器模式,處理 IronBarcode 讀取與寫入操作中的 null 值及空結果。


快速入門:處理BarCode操作中的空結果

請使用 IronBarcode 的守護模式,在存取任何結果屬性之前,安全地檢查 BarcodeResults 集合。 立即開始,只需閱讀並核對以下內容:

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 請複製並執行此程式碼片段。

    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);
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronBarcode

    arrow pointer

如何處理空值與空的BarCode結果?

有兩種失敗模式:若輸入內容不是有效的圖像,則 BarcodeResults 為 null;若圖像中不含 BARCODE,則 BarcodeResults 為空。 若未驗證兩項條件即存取 Value 或進行迭代,將會引發執行時例外。

在進入處理迴圈前,請先檢查以下兩項條件:

輸入

一個 Code128 BarCode 運送標籤(成功路徑)以及一張不含 BarCode 的空白圖片(失敗路徑)。

Code128 barcode encoding SHP-20240001 used as the shipping label input

shipping-label.png (成功路徑)

Blank white image with no barcode used to trigger the empty result path

blank-image.png(失敗路徑,無BarCode)

: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
$vbLabelText   $csharpLabel

每個 BarcodeResult 皆提供 ValueText 字串屬性,兩者皆會傳回解碼後的 BARCODE 內容。 嚴重損毀的BarCode或部分掃描結果可能會產生空值或空白值。 請在每個結果中使用 string.IsNullOrWhiteSpace,以防止空值傳遞至下游系統。

BarcodeReaderOptions 還具備 ConfidenceThreshold 屬性(範圍 0.0 至 1.0),可在低品質讀取資料送達結果集合之前將其過濾掉:

: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
$vbLabelText   $csharpLabel

如何將空安全模式應用於BarCode寫入?

BarcodeWriter.CreateBarcode 接受一個字串值以及 BarcodeWriterEncodingBarcodeEncoding 枚舉。 若傳入 null 或空字串,將立即拋出異常。 格式限制亦需遵守:EAN-8 接受 7 至 8 位數字,UPC-A 接受 11 至 12 位,而 Code 128 則有字元限制。 在呼叫前驗證輸入可避免這些例外情況發生在編碼步驟中:

: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")
$vbLabelText   $csharpLabel

輸出

有效的 7 位數輸入 (1234567) 會產生可掃描的 EAN-8 BARCODE。 空值、空字串或非數值輸入會被守護子句攔截,永遠不會進入編碼步驟。

根據有效的 7 位數輸入 1234567 生成的 EAN-8 BARCODE

寫入 API 也會執行自身的內部驗證:它會檢查校驗和、驗證長度限制,並拒絕選定編碼中的無效字元。 上述防護子句能及早偵測問題,讓呼叫者能掌控錯誤訊息及復原路徑。 有關支援的編碼及其限制之完整清單,請參閱BarCode建立教學"根據資料建立BarCode"指南


如何在後續處理前驗證結果?

當BarCode資料傳入其他系統(例如資料庫寫入、API 呼叫或標籤印表機)時,建議在傳遞資料前,將結果計數、值完整性及類型檢查整合至單一可重複使用的方法中:

輸入

Code128 BarCode 用作驗證器的讀取目標進行倉儲掃描。

Code128 BarCode編碼 WH-SCAN-4471,用於驗證器範例中的倉庫掃描輸入
: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
$vbLabelText   $csharpLabel

此方法會傳回一個空清單而非 null,因此呼叫方無需對回傳值進行 null 檢查。 可選的 expectedType 參數可根據符號系統進行篩選,當掃描從同一張圖像中同時讀取 QR 碼和 Code 128 時,此參數可防止下游系統接收意外的格式。

若需批次讀取多個檔案,請對每個檔案套用相同的處理模式,並彙整結果。 ExpectBarcodeTypes 選項在 BarcodeReaderOptions 上預先將掃描範圍限定於預期的符碼類型,因此送至驗證器的無效結果會減少。


延伸閱讀

當開發流程準備投入生產環境時,請查看授權選項

常見問題

條碼操作中的空值檢查是什麼?

條碼操作中的空值檢查包括驗證條碼結果或輸入是否為空,以防止運行時錯誤並確保流暢的條碼處理。

為什麼空值檢查在C#條碼操作中很重要?

空值檢查在C#條碼操作中至關重要,以避免例外並確保應用程序能夠優雅地處理條碼數據可能丟失或無效的情況。

IronBarcode如何協助進行空值檢查?

IronBarcode提供內建方法,輕鬆處理空值檢查,讓開發者能夠安全管理條碼數據,而不需要手動實施複雜的驗證邏輯。

IronBarcode空值檢查的一些最佳實踐有哪些?

最佳實踐包括檢查BarcodeResults的空值,處理前驗證輸入,並使用信心過濾器以確保可靠的條碼掃描結果。

IronBarcode能否通過信心過濾結果避免空輸出?

是的,IronBarcode允許根據信心水平篩選條碼結果,這有助於減少空輸出並確保條碼讀取的高準確性。

有沒有使用IronBarcode驗證寫入輸入的方法?

IronBarcode能驗證寫入輸入,以確保被編碼成條碼的數據正確且完整,防止條碼生成過程中的問題。

如果空條碼結果未被處理會怎麼樣?

如果不處理空條碼結果,可能導致運行時異常,並破壞應用程序的流程,造成潛在的崩潰或錯誤操作。

IronBarcode如何幫助改善業務流程效率?

IronBarcode通過使條碼生成和讀取快速且準確來提高業務流程效率,減少手動數據輸入錯誤,並改善庫存和資產追蹤。

將IronBarcode實現於專案中需要什麼程式設計技能?

基本的C#程式設計知識足以將IronBarcode實現於專案中,因為它提供了簡單的方法和全面的文檔來指導開發者。

IronBarcode適合於小型專案和大型企業應用嗎?

IronBarcode設計為可擴展且多功能,使其適合小型專案和需要強大條碼解決方案的大型企業應用。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

準備好開始了嗎?
Nuget 下載 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。