如何在 C# 中处理二维码错误信息
IronQR 的错误处理功能可帮助您捕获读取和写入失败,记录诊断信息,并从每次扫描中获得清晰的结果。 如果不添加显式检查,无论是空结果还是损坏的文件都不会返回任何内容,因此您将不知道哪里出了问题。 通过添加有针对性的异常处理和诊断日志记录,您可以将静默故障转化为有用的反馈。 本指南解释了如何处理空结果、管理写入时异常以及为批量处理构建结构化日志包装器。
快速入门:处理二维码错误将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读/写调用包裹在
try-catch块中 - 捕获特定故障的
IOException和ArgumentException - 记录空结果和异常的诊断信息
- 使用结构化 JSON 日志记录实现管道可观测性
处理读取错误和空结果
不记录日志,空结果和损坏的文件对调用者来说看起来是一样的。 以下示例检测文件访问失败,如果扫描未返回任何结果,则发出警告。
输入
此二维码示例输入已存在于磁盘上。 我们将模拟两种情况:一种是用户检索并解码文件,另一种是文件路径不正确。

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,表示二维码读取成功](/static-assets/qr/how-to/detailed-error-messages/success-output-qr.webp)
下面的控制台显示了空结果情况的[ERROR],其中包含文件路径和建议的操作。

处理写入失败
传递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");
}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输出
控制台会显示两种故障情况下的异常类型和消息。

记录异常消息中的输入长度,以确定该问题是否需要更短的内容或更低的修正级别。 对于用户输入,在编码之前验证字符串长度并检查空值,以减少异常开销并改进诊断。
记录二维码操作
使用IronSoftware.Logger来捕获内部诊断信息。 对于每个读取操作,实现一个辅助程序,以 JSON 格式记录文件路径、结果计数和经过时间,以确保整个批次的输出清晰明了。
输入
批处理中包括来自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 日志行:四次成功读取和一条损坏文件的结构化错误条目,然后是批次摘要。 IronQR-debug.log。您可以在这里下载完整的调试日志。

JSON输出直接输入到日志聚合工具中:在容器化部署中将stdout导入Fluentd、Datadog或CloudWatch。 ms字段显示延迟回归,而调试日志捕获了封装器未能捕捉的内部处理步骤。
进一步阅读
-纠错级别:在编码级别调整 QR 码的容错能力。 -如何读取二维码:从头到尾的读取指南。 -二维码生成器教程:生成带样式和徽标的二维码。
- 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 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。