IRONSOFTWAREHOME

如何在C#中處理錯誤和除錯條碼操作

Curtis Chau
Curtis Chau
Updated: 2026年6月29日

條碼處理管道可能會無聲失敗,結果為零常被誤認為'沒有條碼存在'。然而,損壞的文件、受密碼保護的PDF或格式不匹配可能是問題的根源。 實施適當的日誌記錄和結構化的錯誤處理可以揭示失敗並提供可行的診斷。

IronBarcode在BarcodeResult屬性。 這些屬性包括檢測的格式、解碼的值、頁碼和每次成功解碼的坐標。

本教學解釋了如何捕捉並解析型別化異常,從失敗的讀取中提取診斷上下文,啟用結構化日誌,並在批次操作中隔離失敗。

快速開始:處理條碼錯誤並啟用診斷

將讀寫調用包裝在try-catch塊中,針對IronBarcode的型別化異常,提供可行的錯誤資訊而非無聲的失敗。

  1. 1Install IronBarcode with 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}");
    }
    C#
  3. 3部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronBarcode,透過免費試用
    arrow pointer

如何捕捉並解釋IronBarcode異常?

從最具體到最一般地捕捉IronBarcode異常。 排列catch塊以首先處理可行的異常,例如文件、PDF密碼和編碼錯誤,然後處理基類型別。 IronBarCode.Exceptions命名空間定義了11種異常型別,每種對應於特定的失敗模式:

IronBarcode異常型別——原因及推薦解決方案
異常型別觸發器推薦解決方案
IronBarCodeFileException文件損壞、被鎖定或使用不支持的圖像格式驗證文件是受支持的圖像格式且未被鎖定;另外對於缺失的文件可單獨捕捉FileNotFoundException
IronBarCodePdfPasswordExceptionPDF是受密碼保護或加密的通過PdfBarcodeReaderOptions提供密碼,或跳過文件並記錄
IronBarCodeEncodingException條碼生成過程中的通用編碼失敗驗證輸入資料符合目標BarcodeWriterEncoding約束
IronBarCodeContentTooLongEncodingException值超過所選符號的字元限制截斷資料或切換到更高容量格式(QR,DataMatrix)
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException非數字字元傳遞給僅限數字格式(EAN,UPC)清理輸入或切換到字母數字格式(Code128,Code39)
IronBarCodeUnsupportedRendererEncodingException選擇的BarcodeEncoding不能由IronBarcode寫入使用BarcodeWriterEncoding枚舉代替BarcodeEncoding
IronBarCodeParsingException結構化資料(GS1-128)在解析過程中驗證失敗在解析前通過Code128GS1Parser.IsValid()驗證GS1結構
IronBarCodeNativeException本地互操作層錯誤(缺失的DLL,平台不相容)驗證是否安裝了平台特定的NuGet包(BarCode.Linux,BarCode.macOS)
IronBarCodeConfidenceThresholdException無效的信任度門檻參數傳遞給讀取選項確保ConfidenceThreshold在0.0到1.0之間
IronBarCodeUnsupportedException操作不支持當前上下文檢查變更日誌以獲取在您的版本中的功能可用性
IronBarCodeException基類——捕捉任何未匹配以上的IronBarcode特定錯誤記錄完整的異常詳情並升級調查

使用when條款的異常過濾器來路由重疊的異常型別而不進行深層巢狀。 缺少的文件會拋出標準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

IronBarCodeNativeException上將缺少依賴錯誤導向特定處理程式而不影響其他本地異常。 這種方法在Docker部署中特別有用,因為可能缺少平台特定包。

當許可密鑰無效或缺失時,會單獨拋出IronSoftware.Exceptions.LicensingException。 在應用程式啟動時捕捉此異常,而不是在每個讀取或寫入調用時。


如何從失敗的讀取中提取診斷詳情?

返回零結果的讀取操作不是異常; 它將生成一個空的BarcodeResults集合。 診斷上下文通過檢查輸入參數、配置選項和返回的任何部分結果來獲得。

Points(角坐標)。 如果結果存在但不符合預期,首先檢查PageNumber

輸入

一個Code128條碼編碼發票號,讀取時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]塊記錄配置的型別、讀取速度以及建議的下一步操作。

控制台輸出顯示[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)包含無效字節以觸發文件異常。

Code128 barcode encoding ITEM-SQ-001

批次1——掃描1

Code128 barcode encoding ITEM-SQ-002

批次1——掃描2

Code128 barcode encoding ITEM-SQ-003

批次1——掃描3

Code128 barcode encoding ITEM-SQ-004

批次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大於零時為非零)或將錯誤詳情轉發到警報系統。

為了提高吞吐量,通過將MaxParallelThreads以匹配可用的CPU核心。 通過將並行迭代包裹在Parallel.ForEach中並使用執行緒安全集合來維護错误列表的每個文件隔离。


進一步閱讀

查看許可選項當管道準備好投入生產時。

常見問題

如何使用IronBarcode處理條碼操作中的錯誤?

IronBarcode提供型別化異常和內建日誌功能,有效管理和處理條碼操作中的錯誤,確保您的應用順利運行.

IronBarcode提供哪些功能來除錯條碼問題?

IronBarcode包括診斷提取和生產就緒的批量錯誤隔離,幫助開發者有效地識別和解決與條碼相關的問題。

IronBarcode能夠在條碼處理過程中記錄錯誤嗎?

是的,IronBarcode具有內建的日誌記錄功能,允許開發者在條碼處理過程中捕捉並記錄錯誤細節,促進更容易的除錯。

IronBarcode中的型別化異常是什麼?

IronBarcode中的型別化異常是提供有關條碼操作問題的詳細資訊的特定錯誤型別,使得開發者可以更容易地診斷和修復問題。

IronBarcode如何協助進行批量錯誤隔離?

IronBarcode提供生產就緒的批量錯誤隔離功能,有助於將有問題的條碼操作從成功的操作中分離出來,簡化批處理錯誤的管理。

是否有使用IronBarcode從條碼操作中提取診斷的方式?

是的,IronBarcode提供診斷提取工具,幫助開發者收集有關條碼操作的詳細資訊,進而協助除錯和錯誤解決。

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
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

...
閱讀更多

準備好開始了嗎?

Nuget Downloads 2,422,100版本:2026.9剛剛發布

立即獲取您的免費30天試用金鑰
不需要信用卡或帳戶建立
C# NuGet程式庫,用於PDF
通過NuGet安裝

版本: 2026.9

PM > Install-Package BarCode
nuget.org/packages/BarCode/
  1. 在解決方案資源管理器中,右鍵點擊References,管理NuGet包
  2. 選擇瀏覽並搜尋"IronBarCode"
  3. 選擇包並安裝
C# PDF DLL
下載DLL

版本: 2026.9

  1. 下載並解壓IronBarCode至您的Solution目錄中的~/Libs等位置
  2. 在Visual Studio解決方案資源管理器中右鍵點擊References,選擇瀏覽,"IronBarCode.dll"

$999起的授權費用

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費即時演示
Booking Badge

全球數百萬工程師信賴

Iron Software的客戶標誌
獲取您的無義務諮詢
完成下方表單或發送電子郵件至sales@ironsoftware.com
您的詳細資訊將始終保密。
全球數百萬工程師信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立