IRONSOFTWAREHOME

如何在 C# 中处理二维码错误信息

Curtis Chau
Curtis Chau
Updated: 2026年5月9日

IronQR 的错误处理功能可帮助您捕获读取和写入失败,记录诊断信息,并从每次扫描中获得清晰的结果。 如果不添加显式检查,无论是空结果还是损坏的文件都不会返回任何内容,因此您将不知道哪里出了问题。 通过添加有针对性的异常处理和诊断日志记录,您可以将静默故障转化为有用的反馈。 本指南解释了如何处理空结果、管理写入时异常以及为批量处理构建结构化日志包装器。

快速入门:处理二维码错误

将QR读取操作包裹在try-catch块中,并记录文件和解码失败的诊断信息。

  1. 1Install IronQR with NuGet Package Manager

    PM > Install-Package IronQR

  2. 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. 3部署到您的生产环境中进行测试

    通过免费试用立即在您的项目中开始使用IronQR
    arrow pointer

处理读取错误和空结果

不记录日志,空结果和损坏的文件对调用者来说看起来是一样的。 以下示例检测文件访问失败,如果扫描未返回任何结果,则发出警告。

输入

此二维码示例输入已存在于磁盘上。 我们将模拟两种情况:一种是用户检索并解码文件,另一种是文件路径不正确。

有效的二维码输入编码 https://ironsoftware.com/qr/scan-1
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}");
}

输出

终端输出显示 [QRCode] https://ironsoftware.com/qr/scan-1,表示二维码读取成功
请注意: 成功读取只会返回QR码值,而运行时的错误会显示下方的异常消息或警告。

下面的控制台显示了空结果情况的[ERROR],其中包含文件路径和建议的操作。

终端输出显示警告信息:未在 damage-scan.png 中找到二维码;错误信息:未找到 missing-label.png 文件。

处理写入失败

传递IronQrEncodingException。 超出配置纠错级别的数据容量也会抛出异常,因为更高的纠错级别会降低可用数据容量。

输入

下面的两个输入变量定义了失败场景: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");
}

输出

控制台会显示两种故障情况下的异常类型和消息。

终端输出显示 IronQrEncodingException 异常,原因是传递给 QrWriter.Write 的内容为空。

记录异常消息中的输入长度,以确定该问题是否需要更短的内容或更低的修正级别。 对于用户输入,在编码之前验证字符串长度并检查空值,以减少异常开销并改进诊断。


记录二维码操作

使用IronSoftware.Logger来捕获内部诊断信息。 对于每个读取操作,实现一个辅助程序,以 JSON 格式记录文件路径、结果计数和经过时间,以确保整个批次的输出清晰明了。

输入

批处理中包括来自scan-05-broken.png

编码 https://ironsoftware.com/qr/scan-1 的二维码

扫描 1

编码 https://ironsoftware.com/qr/scan-2 的二维码

扫描 2

编码 https://ironsoftware.com/qr/scan-3 的二维码

扫描 3

编码 https://ironsoftware.com/qr/scan-4 的二维码

扫描 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");
C#

输出

控制台显示每个文件的 JSON 日志行:四次成功读取和一条损坏文件的结构化错误条目,然后是批次摘要。 IronQR-debug.log。您可以在这里下载完整的调试日志。

终端输出显示了 4 次成功读取和 1 次错误的 JSON 结构化日志行,Plus批处理完成摘要。

JSON输出直接输入到日志聚合工具中:在容器化部署中将stdout导入Fluentd、Datadog或CloudWatch。 ms字段显示延迟回归,而调试日志捕获了封装器未能捕捉的内部处理步骤。


进一步阅读

-纠错级别:在编码级别调整 QR 码的容错能力。 -如何读取二维码:从头到尾的读取指南。 -二维码生成器教程:生成带样式和徽标的二维码。

准备投入生产时,请查看许可选项

点击这里下载完整的 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
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

...
阅读更多

准备开始了吗?

Nuget Downloads 74,386版本:2026.9刚刚发布

立即获取您的免费30 天试用密钥
无需信用卡或创建账户
C# 用于 PDF 的 NuGet 库
通过 NuGet 安装

版本: 2026.9

PM > Install-Package IronQR
nuget.org/packages/IronQR/
  1. 在解决方案资源管理器中,右键点击引用,管理 NuGet 包
  2. 选择浏览并搜索“IronQR”
  3. 选择包并安装
C# PDF DLL
下载 DLL

版本: 2026.9

  1. 下载并解压IronQR到您的解决方案目录中的~/Libs等位置
  2. 在Visual Studio解决方案资源管理器中,右键单击引用。选择浏览,“IronQR.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 天试用密钥
无需信用卡或创建账户