如何在 C# 中處理錯誤並除錯 BarCode 操作
條碼處理流程可能會悄無聲息地失敗,結果為零通常會被誤認為是「未偵測到條碼」。然而,諸如文件損壞、受密碼保護的 PDF 文件或格式不符等問題都可能是造成這種情況的原因。 實施適當的日誌記錄和結構化的錯誤處理可以發現這些故障並提供可操作的診斷資訊。
IronBarcode 提供 IronBarCode.Exceptions 命名空間中的類型化例外層次結構、內建的日誌記錄 API 以及詳細的 BarcodeResult 屬性。 這些屬性包括偵測到的格式、解碼值、頁碼以及每次成功解碼的座標。
本指南說明如何捕捉並解讀特定類型的例外狀況、從讀取失敗中擷取診斷資訊、啟用結構化日誌記錄,以及在批次操作中隔離失敗。
快速入門:處理BarCode錯誤並啟用診斷功能請將讀寫呼叫封裝在 try-catch 區塊中,並針對 IronBarcode 的類型化例外狀況進行處理,以顯示可採取行動的錯誤訊息,而非靜默失敗。
-
1使用 IronBarcode 安裝 NuGet Package Manager
-
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}"); }Imports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End TryImports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End Try -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronBarcode,並使用 免費試用
如何使用IronBarcode處理條碼錯誤並啟用診斷功能
- 從NuGet下載IronBarcode程式庫
- 將讀寫呼叫封裝在針對特定例外類型的 try-catch 區塊中
- 在成功讀取後,檢查
BarcodeResults是否含有空值或信心度低的項目 - 啟用
IronSoftware.Logger以擷取內部診斷輸出 - 透過「發生錯誤時繼續執行」邏輯,在批次操作中針對每個檔案隔離錯誤
如何捕捉並解讀 IronBarcode 例外狀況?
請依照從最具體到最一般的順序捕捉 IronBarcode 例外狀況。安排 catch 區塊時,先處理可據以採取措施的例外狀況,例如檔案、PDF 密碼和編碼錯誤,再處理基底類型。IronBarCode.Exceptions 命名空間定義了 11 種例外狀況類型,各自對應特定的失敗情況:
| 例外類型 | 觸發 | 建議修正 |
|---|---|---|
IronBarCodeFileException | 檔案已損壞、被鎖定或為不支援的影像格式。 | 驗證文件是否為受支援的影像格式且未被鎖定;同時,對於缺失的文件,單獨捕獲FileNotFoundException 。 |
IronBarCodePdfPasswordException | PDF 檔案受密碼保護或已加密 | 透過 PdfBarcodeReaderOptions 提供密碼,或跳過檔案並記錄 |
IronBarCodeEncodingException | BarCode生成過程中的通用編碼錯誤 | 驗證輸入資料是否符合目標 BarcodeWriterEncoding 的限制條件 |
IronBarCodeContentTooLongEncodingException | 內容超過所選符號集的字元限制 | 截斷資料或切換至更高容量的格式(QR、DataMatrix) |
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException | 傳遞至僅限數字格式的非數字字元(EAN、UPC) | 對輸入資料進行清理或轉換為字母數字格式(Code128、Code39) |
IronBarCodeUnsupportedRendererEncodingException | IronBarcode 無法寫入選定的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 內容的倉庫標籤條碼(失敗情境)。

scanned-invoice.png(成功路徑)

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}");
}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}");
}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 TryImports 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輸出
![主控台輸出顯示 Code128 解碼成功:[Code128] INV-2024-7829](/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-success.webp)
遺失的檔案會觸發 FileNotFoundException,並由專用的 catch 區塊處理。

when (ex.Message.Contains("DLL")) 篩選器套用於 IronBarCodeNativeException,會將缺少相依套件的錯誤導向指定的處理程序,而不影響其他原生例外。這種方式在 Docker 部署中特別實用,因為部署環境可能缺少特定平台的套件。
當授權金鑰無效或缺失時,會單獨拋出IronSoftware.Exceptions.LicensingException。 在應用程式啟動時捕獲此例外狀況,而不是在單一讀取或寫入呼叫周圍捕獲。
如何從讀取失敗中擷取診斷詳細資訊?
讀取操作回傳零結果也不屬於例外; 它會生成一個空的BarcodeResults集合。 透過檢查輸入參數、配置選項和傳回的任何部分結果來取得診斷上下文。
BarcodeResult 物件提供有助於事後分析的屬性,包括 BarcodeType、Value、PageNumber 和 Points(角座標)。 如果結果存在但不如預期,請首先檢查 BarcodeType 與預期格式是否一致,並驗證 PageNumber。
輸入
一個編碼發票號碼的 Code128 條碼,使用設定為 Code128 和 QRCode 的 ExpectBarcodeTypes 來讀取,並且 ReadingSpeed.Detailed 進行全面掃描。

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})");
}
}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})");
}
}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 IfImports 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輸出
ExpectBarcodeTypes匹配圖像中的條碼時,讀取傳回類型、值、頁碼和位置。
如果 ExpectBarcodeTypes 不包含實際的條碼編碼格式,讀取會傳回空結果。[WARN] 區塊會記錄已設定的類型、讀取速度,以及建議採取的下一步措施。
![主控台輸出顯示 [警告] 找不到條碼,ExpectBarcodeTypes 設定為 Code39,但對應的是 Code128 影像](/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-failure.webp)
診斷時常見兩種情況。若 ExpectBarcodeTypes 限定的格式過少而傳回空結果,通常表示條碼使用了其他編碼格式;將範圍擴大為 BarcodeEncoding.All 即可確認。非預期的解碼結果通常表示影像品質不佳。
套用影像濾鏡並以較慢的讀取速度重試,通常可以解決這些問題。您也可以切換 RemoveFalsePositive 選項,排除背景雜訊造成的誤判。
如何啟用條碼操作的詳細日誌記錄?
IronBarcode通過IronSoftware.Logger公開內建的日誌記錄API。 在進行任何條碼操作之前,設定日誌記錄模式和檔案路徑,以擷取讀寫管道的內部診斷輸出。
輸入
啟用詳細日誌記錄時,使用 Code128 條碼 TIFF 影像作為讀取目標。

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.");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.");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.")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同時捕獲除錯輸出和文件級日誌。 日誌檔案記錄內部處理步驟,例如影像預處理階段、格式偵測嘗試和本機互通呼叫,這些步驟無法透過公用 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
}
}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
}
}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 FunctionImports 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結構化輸出可直接與日誌彙整工具整合。在容器化部署中,將 stdout 透過管線傳送至 Fluentd、Datadog 或 CloudWatch。耗時欄位有助於在效能退化導致違反服務等級協定(SLA)之前發現問題。
輸出

如何除錯批次條碼處理?
透過將每個讀取操作隔離到其自身的 try-catch 區塊中來處理多個文件,記錄每個文件的結果,並產生匯總摘要。 即使發生故障,管道也會繼續運行,而不是在遇到第一個錯誤時停止。
輸入
以下是 scans/ 批次目錄中五張 Code128 條碼影像的其中四張。第五個檔案(scan-05-broken.png)含有無效的位元組,用來觸發檔案例外狀況。

批次1 - 掃描1

批次1 - 掃描2

批次1 - 掃描3

批次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}");
}
}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}");
}
}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 IfImports 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輸出

執行過程中,主控台會為每個解碼的條碼輸出一行訊息,接著是包含檔案計數、成功次數、空讀取次數、失敗次數和運行時間的摘要。錯誤訊息會列出對應的檔案名稱和失敗原因。
這個過程區分三種結果類別:成功(找到並解碼條碼)、空(讀取檔案但未偵測到條碼)和失敗(拋出例外)。 這種區別很重要,因為空讀取和讀取失敗需要不同的處理方式。 空讀取可能需要更廣泛的格式設定,而失敗通常表示基礎架構問題,例如缺少檔案、資源被鎖定或缺少本地依賴項。
錯誤清單維護每個文件的上下文,以支援根本原因分析。 在CI/CD管道中,解析此輸出以設定退出程式碼(完全成功為零,failCount大於零時為非零)或將錯誤詳情轉發到警報系統。
若要提高處理量,請將 Multithreaded 設定為 true,並依可用的 CPU 核心數調整 MaxParallelThreads,以啟用平行處理。使用 Parallel.ForEach 執行平行迭代,並以執行緒安全的集合儲存錯誤清單,維持每個檔案的處理隔離。
延伸閱讀
- IronBarcode 教學:讀取條碼:完整的條碼讀取操作說明。
- 防止誤判:減少含有雜訊的影像中的誤判。
- 影像校正方法:提升讀取準確度的濾鏡。
- Docker設定指南:配置正確的本機依賴項的容器化部署。
- BarcodeReaderOptions API參考:完整的配置文件。
- IronBarcode變更日誌:版本特定的修復和功能添加。
處理流程準備好投入正式環境時,請查看授權選項。
常見問題
如何在 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。