如何在 C# 中處理錯誤並除錯 BarCode 操作

Curtis Chau
Curtis Chau
已更新: 2026年8月2日

條碼處理流程可能會悄無聲息地失敗,結果為零通常會被誤認為是「未偵測到條碼」。然而,諸如文件損壞、受密碼保護的 PDF 文件或格式不符等問題都可能是造成這種情況的原因。 實施適當的日誌記錄和結構化的錯誤處理可以發現這些故障並提供可操作的診斷資訊。

IronBarcode 提供 IronBarCode.Exceptions 命名空間中的類型化例外層次結構、內建的日誌記錄 API 以及詳細的 BarcodeResult 屬性。 這些屬性包括偵測到的格式、解碼值、頁碼以及每次成功解碼的座標。

本指南說明如何捕捉並解讀特定類型的例外狀況、從讀取失敗中擷取診斷資訊、啟用結構化日誌記錄,以及在批次操作中隔離失敗。

快速入門:處理BarCode錯誤並啟用診斷功能

請將讀寫呼叫封裝在 try-catch 區塊中,並針對 IronBarcode 的類型化例外狀況進行處理,以顯示可採取行動的錯誤訊息,而非靜默失敗。

  1. 1使用 IronBarcode 安裝 NuGet Package Manager

    PM > Install-Package BarCode

  2. 2複製並運行這段程式碼。

    using IronBarCode;
    using IronBarCode.Exceptions;
    
    try
    {
        BarcodeResults results = BarcodeReader.Read("label.pdf");
        Console.WriteLine($"Found {results.Count} barcode(s)");
    }
    catch (IronBarCodeFileException ex)
    {
        Console.Error.WriteLine($"File error: {ex.Message}");
    }
  3. 3部署到您的生產環境進行測試

    立即在您的項目中開始使用 IronBarcode,並使用 免費試用
    arrow pointer

如何捕捉並解讀 IronBarcode 例外狀況?

請依照從最具體到最一般的順序捕捉 IronBarcode 例外狀況。安排 catch 區塊時,先處理可據以採取措施的例外狀況,例如檔案、PDF 密碼和編碼錯誤,再處理基底類型。IronBarCode.Exceptions 命名空間定義了 11 種例外狀況類型,各自對應特定的失敗情況:

IronBarcode例外狀況類型 - 原因及推薦修復
例外類型觸發建議修正
IronBarCodeFileException檔案已損壞、被鎖定或為不支援的影像格式。驗證文件是否為受支援的影像格式且未被鎖定;同時,對於缺失的文件,單獨捕獲FileNotFoundException 。
IronBarCodePdfPasswordExceptionPDF 檔案受密碼保護或已加密透過 PdfBarcodeReaderOptions 提供密碼,或跳過檔案並記錄
IronBarCodeEncodingExceptionBarCode生成過程中的通用編碼錯誤驗證輸入資料是否符合目標 BarcodeWriterEncoding 的限制條件
IronBarCodeContentTooLongEncodingException內容超過所選符號集的字元限制截斷資料或切換至更高容量的格式(QR、DataMatrix)
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException傳遞至僅限數字格式的非數字字元(EAN、UPC)對輸入資料進行清理或轉換為字母數字格式(Code128、Code39)
IronBarCodeUnsupportedRendererEncodingExceptionIronBarcode 無法寫入選定的BarcodeEncoding請使用 BarcodeWriterEncoding 列舉,而非 BarcodeEncoding
IronBarCodeParsingException結構化資料 (GS1-128) 在解析過程中驗證失敗在解析前,請使用 Code128GS1Parser.IsValid() 驗證 GS1 結構
IronBarCodeNativeException原生互通層發生錯誤(缺少 DLL 檔案、平台不相容)請確認已安裝特定平台的 NuGet 套件(BarCode.Linux、BarCode.macOS)
IronBarCodeConfidenceThresholdException傳遞給 reader 選項的信心閾值參數無效請確保 ConfidenceThreshold 值介於 0.0 至 1.0 之間
IronBarCodeUnsupportedException當前上下文中不支援此操作檢查變更日誌以確認您的版本中功能的可用性
IronBarCodeException基礎類型 - 捕獲任何未在上面匹配的IronBarcode特定錯誤記錄完整的例外情況詳細資訊,並上報以進行調查

使用含有 when 子句的例外狀況篩選器,將重疊的例外狀況類型導向適當的處理程序,避免深層巢狀結構。遺失的檔案會擲回標準的 System.IO.FileNotFoundException,而非 IronBarCodeFileException,因此請針對這種情況加入獨立的 catch 區塊:

輸入

一個編碼發票號碼的 Code128 條碼(成功情境),以及代表遺失 PDF 內容的倉庫標籤條碼(失敗情境)。

Code128 條碼編碼 INV-2024-7829 用作掃描發票輸入

scanned-invoice.png(成功路徑)

代表遺失的 warehouse-labels.pdf 失敗路徑輸入內容的 Code128 條碼

warehouse-labels.pdf(失敗路徑 - 文件未在磁碟上存在)

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}");
}

輸出

請注意: 有效的文件將解析為解碼的條碼類型和值。
主控台輸出顯示 Code128 解碼成功:[Code128] INV-2024-7829

遺失的檔案會觸發 FileNotFoundException,並由專用的 catch 區塊處理。

主控台輸出顯示缺少 warehouse-labels.pdf 文件,並出現 FileNotFoundException 例外狀況。

when (ex.Message.Contains("DLL")) 篩選器套用於 IronBarCodeNativeException,會將缺少相依套件的錯誤導向指定的處理程序,而不影響其他原生例外。這種方式在 Docker 部署中特別實用,因為部署環境可能缺少特定平台的套件。

當授權金鑰無效或缺失時,會單獨拋出IronSoftware.Exceptions.LicensingException。 在應用程式啟動時捕獲此例外狀況,而不是在單一讀取或寫入呼叫周圍捕獲。


如何從讀取失敗中擷取診斷詳細資訊?

讀取操作回傳零結果也不屬於例外; 它會生成一個空的BarcodeResults集合。 透過檢查輸入參數、配置選項和傳回的任何部分結果來取得診斷上下文。

BarcodeResult 物件提供有助於事後分析的屬性,包括 BarcodeType、Value、PageNumber 和 Points(角座標)。 如果結果存在但不如預期,請首先檢查 BarcodeType 與預期格式是否一致,並驗證 PageNumber。

輸入

一個編碼發票號碼的 Code128 條碼,使用設定為 Code128 和 QRCode 的 ExpectBarcodeTypes 來讀取,並且 ReadingSpeed.Detailed 進行全面掃描。

Code128 條碼編碼 INV-2024-7829 用作掃描發票輸入
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})");
    }
}

輸出

請注意: 當ExpectBarcodeTypes匹配圖像中的條碼時,讀取傳回類型、值、頁碼和位置。
主控台輸出顯示 Code128 解碼成功,並顯示了頁碼和位置座標。

如果 ExpectBarcodeTypes 不包含實際的條碼編碼格式,讀取會傳回空結果。[WARN] 區塊會記錄已設定的類型、讀取速度,以及建議採取的下一步措施。

主控台輸出顯示 [警告] 找不到條碼,ExpectBarcodeTypes 設定為 Code39,但對應的是 Code128 影像

診斷時常見兩種情況。若 ExpectBarcodeTypes 限定的格式過少而傳回空結果,通常表示條碼使用了其他編碼格式;將範圍擴大為 BarcodeEncoding.All 即可確認。非預期的解碼結果通常表示影像品質不佳。

套用影像濾鏡並以較慢的讀取速度重試,通常可以解決這些問題。您也可以切換 RemoveFalsePositive 選項,排除背景雜訊造成的誤判。

如何啟用條碼操作的詳細日誌記錄?

IronBarcode通過IronSoftware.Logger公開內建的日誌記錄API。 在進行任何條碼操作之前,設定日誌記錄模式和檔案路徑,以擷取讀寫管道的內部診斷輸出。

輸入

啟用詳細日誌記錄時,使用 Code128 條碼 TIFF 影像作為讀取目標。

Code128 條碼編碼 PROB-SCAN-999 用作日誌記錄範例中的問題掃描輸入
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同時捕獲除錯輸出和文件級日誌。 日誌檔案記錄內部處理步驟,例如影像預處理階段、格式偵測嘗試和本機互通呼叫,這些步驟無法透過公用 API 查看。

對於使用結構化日誌框架(Serilog、NLog、Microsoft.Extensions.Logging)的正式環境處理流程,可在中介軟體層封裝 IronBarcode 操作,在內建日誌檔之外加入結構化 JSON 記錄。內建記錄器寫入的純文字診斷資訊有助於將問題轉交技術支援處理;結構化封裝則可為可觀測性工具提供可查詢的欄位。

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
    }
}

結構化輸出可直接與日誌彙整工具整合。在容器化部署中,將 stdout 透過管線傳送至 Fluentd、Datadog 或 CloudWatch。耗時欄位有助於在效能退化導致違反服務等級協定(SLA)之前發現問題。

輸出

主控台輸出顯示條碼讀取成功(已啟用詳細日誌記錄),並顯示了日誌檔案路徑。

如何除錯批次條碼處理?

透過將每個讀取操作隔離到其自身的 try-catch 區塊中來處理多個文件,記錄每個文件的結果,並產生匯總摘要。 即使發生故障,管道也會繼續運行,而不是在遇到第一個錯誤時停止。

輸入

以下是 scans/ 批次目錄中五張 Code128 條碼影像的其中四張。第五個檔案(scan-05-broken.png)含有無效的位元組,用來觸發檔案例外狀況。

編碼 ITEM-SQ-001 的 Code128 條碼

批次1 - 掃描1

編碼 ITEM-SQ-002 的 Code128 條碼

批次1 - 掃描2

編碼 ITEM-SQ-003 的 Code128 條碼

批次1 - 掃描3

編碼 ITEM-SQ-004 的 Code128 條碼

批次1 - 掃描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 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}");
    }
}

輸出

主控台輸出顯示批次摘要:4 個成功,1 個失敗,並包含損壞檔案的錯誤詳細資料。

執行過程中,主控台會為每個解碼的條碼輸出一行訊息,接著是包含檔案計數、成功次數、空讀取次數、失敗次數和運行時間的摘要。錯誤訊息會列出對應的檔案名稱和失敗原因。

這個過程區分三種結果類別:成功(找到並解碼條碼)、空(讀取檔案但未偵測到條碼)和失敗(拋出例外)。 這種區別很重要,因為空讀取和讀取失敗需要不同的處理方式。 空讀取可能需要更廣泛的格式設定,而失敗通常表示基礎架構問題,例如缺少檔案、資源被鎖定或缺少本地依賴項。

錯誤清單維護每個文件的上下文,以支援根本原因分析。 在CI/CD管道中,解析此輸出以設定退出程式碼(完全成功為零,failCount大於零時為非零)或將錯誤詳情轉發到警報系統。

若要提高處理量,請將 Multithreaded 設定為 true,並依可用的 CPU 核心數調整 MaxParallelThreads,以啟用平行處理。使用 Parallel.ForEach 執行平行迭代,並以執行緒安全的集合儲存錯誤清單,維持每個檔案的處理隔離。


延伸閱讀

處理流程準備好投入正式環境時,請查看授權選項。

常見問題

如何在 C#中使用 IronBarcode 處理條碼錯誤?

您可以通過使用 IronBarCode.Exceptions 命名空間中的類型化例外層次結構來處理 C#中的條碼錯誤。這允許您捕獲與文件錯誤、PDF 密碼、編碼問題等相關的特定例外。實施結構化日誌記錄並使用 BarcodeResult 屬性可以幫助高效診斷和隔離問題。

IronBarcode 常見的例外有哪些?

IronBarcode 可能拋出各種例外,例如與文件相關問題的 IronBarCodeFileException、對於受密碼保護的 PDF 的 IronBarCodePdfPasswordException 和編碼失敗的 IronBarCodeEncodingException。每種類型的例外都提供詳細的診斷信息,以幫助解決條碼處理過程中遇到的特定錯誤。

如何在 IronBarcode 中啟用診斷日誌記錄?

要在 IronBarcode 中啟用診斷日誌記錄,請在任何條碼操作之前使用 IronSoftware.Logger 設置日誌模式和文件路徑。這將捕獲內部處理步驟並藉由將日誌寫入指定文件來幫助跟蹤問題。

如果 IronBarcode 中的條碼讀取操作返回零結果,應該怎麼辦?

如果 IronBarcode 中的條碼讀取操作返回零結果,則表示沒有條碼符合配置的選項。檢查您的輸入參數和選項,例如 ExpectBarcodeTypes 及 ReadingSpeed,並考慮擴大符號期望或調整讀取速度以進行更全面的掃描。

IronBarcode 可以處理缺失本機依賴項的例外嗎?

是的,IronBarcode 通過 IronBarCodeNativeException 處理缺失本機依賴項的例外。您可以篩選這些例外以識別缺失的 DLL 或平台依賴項,在 Docker 環境中特別有用。

如何使用 IronBarcode 調試批量條碼處理?

為了在 IronBarcode 中調試批量條碼處理,請將每次讀取操作隔離於其自己的 try-catch 區塊中並捕獲每個文件的錯誤。此方法確保批量操作可以在失敗的情況下繼續運行,並生成包含成功、失敗及空結果的摘要。

如何在 IronBarcode 中有效捕獲和解釋例外?

在 IronBarcode 中捕獲和解釋例外,請將您的 try-catch 區塊從具體到一般排序。從如文件錯誤或 PDF 密碼問題等可採取行動的例外開始,並以基礎的 IronBarCodeException 結束,以確保全面的錯誤處理。

BarcodeResult 的哪些屬性可用於事後分析?

IronBarcode 中的 BarcodeResult 對象提供 BarcodeType、Value、PageNumber 和 Points (座標) 等屬性用於事後分析。這些屬性有助於通過檢查實際與預期條碼類型及驗証頁碼來了解意外結果。

在 IronBarcode 中,如何防止條碼讀取中的誤報?

為了在 IronBarcode 中防止條碼讀取中的誤報,您可以使用圖像濾鏡來提高圖像質量和使用 RemoveFalsePositive 選項。此外,調整讀取速度和 ExpectBarcodeTypes 可以減少嘈雜背景導致的錯誤。

IronBarcode 如何處理加密 PDF 的錯誤?

IronBarcode 使用 IronBarCodePdfPasswordException 處理來自加密 PDF 的錯誤。要處理此類文件,提供密碼使用 PdfBarcodeReaderOptions 或記錄並跳過它們以進行不間斷的條碼處理。

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

閱讀更多

準備好開始了嗎?

NuGet 下載次數 2,575,633版本:2026.11剛剛發布