如何在 C# 中處理 QR Code 錯誤資訊

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

IronQR 的錯誤處理協助您捕捉讀取和寫入失敗、記錄診斷資訊,並從每次掃描中獲得明確的結果。 如果您不新增明確的檢查,空結果和損壞的文件都將返回空值,因此您不會知道出了什麼問題。 通過新增有針對性的異常處理和診斷記錄,您可以將靜默失敗轉化為有用的反饋。 本指南說明如何處理空結果、管理寫入時的異常,並為批次處理構建結構化的記錄包裝器。

快速入門:處理 QR Code 錯誤

將 QR 讀取操作封裝在 try-catch 區塊中,並記錄文件和解碼失敗的診斷資訊。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronQR

    PM > Install-Package IronQR
  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}");
    }
  3. 部署以在您的實時環境中測試

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

    arrow pointer

處理讀取錯誤和空結果

如果沒有記錄,呼叫者看來空結果和損壞的文件是無法分辨的。 以下範例檢測文件存取失敗並在掃描未返回結果時發出警告。

輸入

此 QR 範例輸入存在於磁碟上。 我們將模擬兩種情景:一種是使用者檢索並解碼文件,另一種是文件路徑不正確。

有效的 QR code 輸入編碼 https://ironsoftware.com/qr/scan-1
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/read-diagnostics.cs
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
$vbLabelText   $csharpLabel

輸出

終端輸出顯示[QRCode] https://ironsoftware.com/qr/scan-1 為成功的 QR code 讀取

請注意成功的讀取僅返回 QR code 值,而運行時發生錯誤時將顯示異常資訊或警告,如下所示。

下面的控制台顯示了 [WARN] 用於空結果情況和 [ERROR] 用於缺少文件,其中包含每個文件路徑和建議的操作。

終端輸出顯示 WARN 提示在 damaged-scan.png 中未找到 QR code 和 ERROR 文件未找到對於 missing-label.png

處理寫入失敗

null 傳遞給 QrWriter.Write,會觸發 IronQrEncodingException。 超過配置的錯誤更正等級容量的資料也將引發異常,因為較高的更正等級會減少可用的資料容量。

輸入

下面的兩個輸入變數定義了失敗場景:nullContentoversizedContent 是一個超過最高更正等級 QR 容量的 5,000 字串。

:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/write-diagnostics.cs
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
$vbLabelText   $csharpLabel

輸出

控制台顯示了兩個失敗場景的異常型別和資訊。

終端輸出顯示傳遞給 QrWriter.Write 的空內容的 IronQrEncodingException

與異常資訊一起記錄輸入長度,以確定該問題是否需要更短內容或較低的更正等級。 對於使用者輸入,請在編碼之前驗證字串長度並檢查空值,以減少異常開銷並改善診斷結果。


記錄 QR Code 操作

using IronSoftware.Logger 來捕捉內部診斷資訊。 對於每個讀取操作,實現一個助手,將文件路徑、結果計數和耗時作為 JSON 記錄下來,以確保對整個批次有明確的輸出。

輸入

批次包括來自 qr-scans/ 的四個有效 QR code 圖片以及一個具有無效位元組的第五個文件 scan-05-broken.png

編碼 https://ironsoftware.com/qr/scan-1 的 QR 碼
編碼 https://ironsoftware.com/qr/scan-2 的 QR 碼
編碼 https://ironsoftware.com/qr/scan-3 的 QR 碼
編碼 https://ironsoftware.com/qr/scan-4 的 QR 碼
:path=/static-assets/qr/content-code-examples/how-to/detailed-error-messages/logging-wrapper.cs
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");
Imports IronQr
Imports IronSoftware.Drawing
Imports System.Diagnostics
Imports System.IO
Imports System.Linq

' 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
Private Function ReadQrWithDiagnostics(filePath As String) As (Results As IEnumerable(Of QrResult), Success As Boolean, Error As String)
    Dim sw = Stopwatch.StartNew()
    Try
        Dim input = New QrImageInput(AnyBitmap.FromFile(filePath))
        Dim 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, Nothing)
    Catch ex As Exception
        sw.Stop()
        Dim error As String = $"{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(Of QrResult)(), False, error)
    End Try
End Function

' Usage: process a batch with per-file isolation
Dim files As String() = Directory.GetFiles("qr-scans/", "*.png")
Dim ok As Integer = 0, fail As Integer = 0

For Each file As String In files
    Dim result = ReadQrWithDiagnostics(file)
    Dim results = result.Results
    Dim success = result.Success
    Dim error = result.Error

    If success AndAlso results.Any() Then
        ok += 1
    Else
        fail += 1
    End If
Next

Console.WriteLine($"\nBatch complete: {ok} success, {fail} failed/empty out of {files.Length} files")
$vbLabelText   $csharpLabel

輸出

控制台顯示每個文件的 JSON 記錄行:四次成功讀取和一個結構化的錯誤輸入文件的錯誤條目,隨後是批次摘要。 IronSoftware.Logger 同時將內部診斷資訊寫入 IronQR-debug.log。您可以在這裡下載完整的除錯日志。

終端輸出顯示 4 次成功讀取和 1 次錯誤的 JSON 結構化記錄行,加上批次完成摘要

JSON 輸出直接饋送到記錄聚合工具:將 stdout 傳送到 Fluentd、Datadog 或 CloudWatch 中的容器化部署中。 ms 欄位顯示延遲倒退,除錯日志捕獲包裝器未捕獲的內部處理步驟。


進一步閱讀

查看授權選項,當您準備好生產時。

點擊此處下載完整的 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#程式碼中妥善的例外處理來管理。

Curtis Chau
技術作家

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

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備好開始了嗎?
Nuget 下載 70,398 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在滾動?

想要快速證明嗎? PM > Install-Package IronQR
執行一個範例 觀看您的URL變成QR碼。