如何在 C# 中處理 QR Code 錯誤資訊
IronQR 的錯誤處理協助您捕捉讀取和寫入失敗、記錄診斷資訊,並從每次掃描中獲得明確的結果。 如果您不新增明確的檢查,空結果和損壞的文件都將返回空值,因此您不會知道出了什麼問題。 通過新增有針對性的異常處理和診斷記錄,您可以將靜默失敗轉化為有用的反饋。 本指南說明如何處理空結果、管理寫入時的異常,並為批次處理構建結構化的記錄包裝器。
快速入門:處理 QR Code 錯誤將 QR 讀取操作封裝在 try-catch 區塊中,並記錄文件和解碼失敗的診斷資訊。
-
1Install IronQR with NuGet Package Manager
-
2複製並運行這段程式碼片段。
using IronQr; using IronSoftware.Drawing; try { var input = new QrImageInput(AnyBitmap.FromFile("label.png")); var results = new QrReader().Read(input); Console.WriteLine($"Found {results.Count()} QR code(s)"); } catch (IOException ex) { Console.Error.WriteLine($"File error: {ex.Message}"); }C# -
3部署以在您的實時環境中測試
今天就開始在您的專案中使用IronQR,透過免費試用
最小化工作流程(共5步)
- 下載 IronQR C# 程式庫以處理 QR code 錯誤
- 將 QR 讀取/寫入調用包裹在
try-catch區塊中 - 捕捉
IOException和ArgumentException以應對特定的失敗 - 記錄空結果和異常的診斷資訊
- 使用結構化的 JSON 記錄管線可觀測性
處理讀取錯誤和空結果
如果沒有記錄,呼叫者看來空結果和損壞的文件是無法分辨的。 以下範例檢測文件存取失敗並在掃描未返回結果時發出警告。
輸入
此 QR 範例輸入存在於磁碟上。 我們將模擬兩種情景:一種是使用者檢索並解碼文件,另一種是文件路徑不正確。

using IronQr;
using IronSoftware.Drawing;
string filePath = "damaged-scan.png";
try
{
// File-level failure throws IOException or FileNotFoundException
var inputBmp = AnyBitmap.FromFile(filePath);
var imageInput = new QrImageInput(inputBmp);
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(imageInput);
if (!results.Any())
{
// Not an exception — but a diagnostic event worth logging
Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}");
Console.Error.WriteLine($" Action: Verify image quality or try a different scan");
}
else
{
foreach (QrResult result in results)
{
Console.WriteLine($"[{result.QrType}] {result.Value}");
}
}
}
catch (FileNotFoundException)
{
Console.Error.WriteLine($"[ERROR] File not found: {filePath}");
}
catch (IOException ex)
{
Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}");
}Imports IronQr
Imports IronSoftware.Drawing
Module Module1
Sub Main()
Dim filePath As String = "damaged-scan.png"
Try
' File-level failure throws IOException or FileNotFoundException
Dim inputBmp = AnyBitmap.FromFile(filePath)
Dim imageInput = New QrImageInput(inputBmp)
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(imageInput)
If Not results.Any() Then
' Not an exception — but a diagnostic event worth logging
Console.Error.WriteLine($"[WARN] No QR codes found in: {filePath}")
Console.Error.WriteLine(" Action: Verify image quality or try a different scan")
Else
For Each result As QrResult In results
Console.WriteLine($"[{result.QrType}] {result.Value}")
Next
End If
Catch ex As FileNotFoundException
Console.Error.WriteLine($"[ERROR] File not found: {filePath}")
Catch ex As IOException
Console.Error.WriteLine($"[ERROR] Cannot read file: {filePath} — {ex.Message}")
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] Unexpected failure reading {filePath}: {ex.GetType().Name} — {ex.Message}")
End Try
End Sub
End Module輸出
![終端輸出顯示[QRCode] https://ironsoftware.com/qr/scan-1 為成功的 QR code 讀取](/static-assets/qr/how-to/detailed-error-messages/success-output-qr.webp)
下面的控制台顯示了 [WARN] 用於空結果情況和 [ERROR] 用於缺少文件,其中包含每個文件路徑和建議的操作。

處理寫入失敗
將 null 傳遞給 QrWriter.Write,會觸發 IronQrEncodingException。 超過配置的錯誤更正等級容量的資料也將引發異常,因為較高的更正等級會減少可用的資料容量。
輸入
下面的兩個輸入變數定義了失敗場景:nullContent 是 oversizedContent 是一個超過最高更正等級 QR 容量的 5,000 字串。
using IronQr;
string? content = null; // null throws IronQrEncodingException
string oversizedContent = new string('A', 5000); // 5,000 chars exceeds QR capacity at Highest error correction level
// Scenario 1: null input
try
{
QrCode qr = QrWriter.Write(content); // Input
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}"); // Output
}
// Scenario 2: data exceeds QR capacity at the configured error correction level
try
{
var options = new QrOptions(QrErrorCorrectionLevel.Highest);
QrCode qr = QrWriter.Write(oversizedContent, options); // Input
}
catch (Exception ex)
{
Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}"); // Output
Console.Error.WriteLine($" Input length: {oversizedContent.Length} chars");
Console.Error.WriteLine($" Action: Reduce content or lower error correction level");
}Imports IronQr
Dim content As String = Nothing ' Nothing throws IronQrEncodingException
Dim oversizedContent As String = New String("A"c, 5000) ' 5,000 chars exceeds QR capacity at Highest error correction level
' Scenario 1: null input
Try
Dim qr As QrCode = QrWriter.Write(content) ' Input
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] Null content: {ex.GetType().Name} — {ex.Message}") ' Output
End Try
' Scenario 2: data exceeds QR capacity at the configured error correction level
Try
Dim options As New QrOptions(QrErrorCorrectionLevel.Highest)
Dim qr As QrCode = QrWriter.Write(oversizedContent, options) ' Input
Catch ex As Exception
Console.Error.WriteLine($"[ERROR] QR capacity exceeded: {ex.Message}") ' Output
Console.Error.WriteLine($" Input length: {oversizedContent.Length} chars")
Console.Error.WriteLine(" Action: Reduce content or lower error correction level")
End Try輸出
控制台顯示了兩個失敗場景的異常型別和資訊。

與異常資訊一起記錄輸入長度,以確定該問題是否需要更短內容或較低的更正等級。 對於使用者輸入,請在編碼之前驗證字串長度並檢查空值,以減少異常開銷並改善診斷結果。
記錄 QR Code 操作
using IronSoftware.Logger 來捕捉內部診斷資訊。 對於每個讀取操作,實現一個助手,將文件路徑、結果計數和耗時作為 JSON 記錄下來,以確保對整個批次有明確的輸出。
輸入
批次包括來自 qr-scans/ 的四個有效 QR code 圖片以及一個具有無效位元組的第五個文件 scan-05-broken.png。

掃描 1

掃描 2

掃描 3

掃描 4
using IronQr;
using IronSoftware.Drawing;
using System.Diagnostics;
// Enable shared Iron Software logging for internal diagnostics
IronQr.Logging.Logger.LoggingMode = IronQr.Logging.Logger.LoggingModes.All;
IronQr.Logging.Logger.LogFilePath = "ironqr-debug.log";
// Reusable wrapper for structured observability
(IEnumerable<QrResult> Results, bool Success, string Error) ReadQrWithDiagnostics(string filePath)
{
var sw = Stopwatch.StartNew();
try
{
var input = new QrImageInput(AnyBitmap.FromFile(filePath));
var results = new QrReader().Read(input).ToList();
sw.Stop();
Console.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
+ $"\"status\":\"ok\",\"count\":{results.Count},\"ms\":{sw.ElapsedMilliseconds}}}");
return (results, true, null);
}
catch (Exception ex)
{
sw.Stop();
string error = $"{ex.GetType().Name}: {ex.Message}";
Console.Error.WriteLine($"{{\"op\":\"qr_read\",\"file\":\"{Path.GetFileName(filePath)}\","
+ $"\"status\":\"error\",\"exception\":\"{ex.GetType().Name}\","
+ $"\"message\":\"{ex.Message}\",\"ms\":{sw.ElapsedMilliseconds}}}");
return (Enumerable.Empty<QrResult>(), false, error);
}
}
// Usage: process a batch with per-file isolation
string[] files = Directory.GetFiles("qr-scans/", "*.png");
int ok = 0, fail = 0;
foreach (string file in files)
{
var (results, success, error) = ReadQrWithDiagnostics(file);
if (success && results.Any()) ok++;
else fail++;
}
Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files");
輸出
控制台顯示每個文件的 JSON 記錄行:四次成功讀取和一個結構化的錯誤輸入文件的錯誤條目,隨後是批次摘要。 IronSoftware.Logger 同時將內部診斷資訊寫入 IronQR-debug.log。您可以在這裡下載完整的除錯日志。

JSON 輸出直接饋送到記錄聚合工具:將 stdout 傳送到 Fluentd、Datadog 或 CloudWatch 中的容器化部署中。 ms 欄位顯示延遲倒退,除錯日志捕獲包裝器未捕獲的內部處理步驟。
進一步閱讀
- 錯誤更正等級:在編碼級別調整 QR 的彈性。
- 讀取 QR Code 的操作指南:端到端的讀取操作指南。
- QR Code 生成器教程:含有風格和標誌的生成器。
- QrReader API參考:方法簽名與備註。
- QrWriter API 參考:所有
Write重載。
查看授權選項,當您準備好生產時。
點擊此處下載完整的 DetailedErrorMessagesTest 控制台應用專案。
常見問題
如何在C#中偵錯QR碼的讀取/寫入操作?
您可以使用IronQR在C#中偵錯QR碼的讀取/寫入操作,通過捕捉例外、記錄診斷資訊、並透過結構化輸出監控批次處理。
如果我在C#中處理QR碼時遇到錯誤,該怎麼辦?
如果您在C#中處理QR碼時遇到錯誤,請使用IronQR來捕捉和處理例外。這將允許您有效識別和解決問題。
IronQR如何幫助監控QR碼的批次處理?
IronQR通過提供結構化輸出來幫助監控QR碼的批次處理,有助於識別和解決處理過程中的任何錯誤或效率低下的地方。
IronQR可以為QR碼操作記錄診斷資訊嗎?
是的,IronQR可以為QR碼操作記錄診斷資訊,使您能在C#應用中追蹤和分析性能和錯誤。
使用IronQR處理QR碼時的常見例外有哪些?
使用IronQR處理QR碼時的常見例外包括與無法讀取的QR碼及不正確的格式處理有關的問題,這些可以通過在C#程式碼中妥善的例外處理來管理。
How can I improve error detection during QR code processing with IronQR?
Improve error detection by implementing logging that captures detailed information on file paths, operation status, result counts, and execution time. This data supports easier debugging and system observability.
Can IronQR's logging output be integrated with log aggregation tools?
Yes, the JSON output from IronQR can be fed directly into log aggregation tools such as Fluentd, Datadog, or CloudWatch, making it suitable for containerized deployments and enhancing monitoring capabilities.
What approach does IronQR suggest for handling batch QR code operations?
IronQR recommends processing each file in isolation, logging the results for each read operation to help identify errors, and providing a complete batch summary that tallies successes and failures.
How does IronQR assist in diagnosing file-level failures during QR code scans?
IronQR detects file-level failures like IOException and FileNotFoundException, providing descriptive error messages which can be logged to pinpoint issues such as incorrect file paths or unreadable files.
Why is it important to wrap QR read/write calls in try-catch blocks?
Wrapping read/write operations in try-catch blocks ensures that failures do not crash the application, allowing you to handle exceptions gracefully, log necessary diagnostics, and guide the user with useful messages.

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