如何在 C# 中验证二维码校验和并应用容错机制
处理印刷标签、相机拍摄的图像或扫描文档等实际输入时,二维码处理流程可能遇到两种情况:二维码损坏严重,无法解码;或者解码结果通过了校验和验证,却未通过业务校验。
解码时,里德-所罗门纠错会自动尝试修复因二维码损坏而受影响的数据。若无法恢复二维码,会返回空结果集合,不会返回部分解码结果。应用层仍需单独验证解码值,例如在继续处理之前检查值是否非空、是否符合预期格式,或是否包含有效的 URI。
本指南介绍如何使用 IronQR 库验证二维码校验和并执行容错检查。
快速入门:验证二维码校验和读取二维码并检查解码是否成功:结果集合非空表示里德-所罗门校验已通过。
-
1使用 IronQR 安装 NuGet Package Manager
-
2复制并运行这段代码。
using IronQr; using IronSoftware.Drawing; var reader = new QrReader(); IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("label.png"))); if (!results.Any()) { Console.WriteLine("No QR code detected or decoding failed."); return; } Console.WriteLine(results.First().Value);Imports IronQr Imports IronSoftware.Drawing Dim reader = New QrReader() Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("label.png"))) If Not results.Any() Then Console.WriteLine("No QR code detected or decoding failed.") Return End If Console.WriteLine(results.First().Value)Imports IronQr Imports IronSoftware.Drawing Dim reader = New QrReader() Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("label.png"))) If Not results.Any() Then Console.WriteLine("No QR code detected or decoding failed.") Return End If Console.WriteLine(results.First().Value) -
3部署到您的生产环境中进行测试
今天就用免费试用在您的项目中开始使用IronQR
基本流程(5 个步骤)
- 下载 IronQR C# 库以验证二维码校验和
- 使用
QrImageInput加载图片 - 调用
QrReader.Read方法解码图像并自动执行里德-所罗门校验 - 检查结果集合以确认解码是否成功,因为空集合表示解码失败。
- 在将解码值传递给下游之前,请根据应用程序要求验证解码后的值。
验证二维码校验和
二维码通过里德-所罗门纠错检测并修复编码数据中的错误。纠错级别(低 7%、中 15%、较高(Q)25%、高 30%)决定了在仍能恢复数据的前提下,可丢失的码字比例。
读取二维码时,解码过程会在内部验证校验和。QrResult 类未提供置信度属性。结果集合中存在结果表示校验通过,解码失败时则返回空集合。
输入
该产品标签上的二维码编码了 https://ironsoftware.com/,生成时采用中等纠错级别。此示例模拟标签在运输过程中被经手或轻微刮擦的情况。

using IronQr;
using IronSoftware.Drawing;
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("damaged-label.png")));
// Reed-Solomon decoding is pass/fail — presence in results means valid checksum
if (!results.Any())
{
// Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.");
return;
}
foreach (QrResult result in results)
{
// Decoded successfully — validate the content matches expected format
if (string.IsNullOrWhiteSpace(result.Value))
{
Console.WriteLine("QR decoded but produced an empty value.");
continue;
}
Console.WriteLine($"Valid QR: {result.Value}");
}using IronQr;
using IronSoftware.Drawing;
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("damaged-label.png")));
// Reed-Solomon decoding is pass/fail — presence in results means valid checksum
if (!results.Any())
{
// Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.");
return;
}
foreach (QrResult result in results)
{
// Decoded successfully — validate the content matches expected format
if (string.IsNullOrWhiteSpace(result.Value))
{
Console.WriteLine("QR decoded but produced an empty value.");
continue;
}
Console.WriteLine($"Valid QR: {result.Value}");
}Imports IronQr
Imports IronSoftware.Drawing
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("damaged-label.png")))
' Reed-Solomon decoding is pass/fail — presence in results means valid checksum
If Not results.Any() Then
' Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.")
Return
End If
For Each result As QrResult In results
' Decoded successfully — validate the content matches expected format
If String.IsNullOrWhiteSpace(result.Value) Then
Console.WriteLine("QR decoded but produced an empty value.")
Continue For
End If
Console.WriteLine($"Valid QR: {result.Value}")
NextImports IronQr
Imports IronSoftware.Drawing
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("damaged-label.png")))
' Reed-Solomon decoding is pass/fail — presence in results means valid checksum
If Not results.Any() Then
' Decoding failed entirely — damage exceeded the error correction capacity
Console.WriteLine("QR code could not be decoded. Consider re-scanning or using a higher error correction level at generation time.")
Return
End If
For Each result As QrResult In results
' Decoded successfully — validate the content matches expected format
If String.IsNullOrWhiteSpace(result.Value) Then
Console.WriteLine("QR decoded but produced an empty value.")
Continue For
End If
Console.WriteLine($"Valid QR: {result.Value}")
Next输出
控制台显示解码值 https://ironsoftware.com/,表明里德-所罗门解码成功,二维码中的数据已完整恢复。

若要提高二维码受损后的可读性,可在生成时选择较高的纠错级别。高纠错级别可在数据丢失比例高达 30% 时恢复数据,但生成的二维码会更大。
读取二维码时识别编码格式
IronQR 支持三种二维码编码格式:标准二维码、微型二维码和矩形微型二维码。读取时会自动识别编码格式,扫描完成后可通过 QrResult.QrType 字段获取对应的枚举值。
扫描模式决定了速度与准确性之间的平衡:Auto 结合机器学习检测与经典扫描,OnlyDetectionModel 仅使用ML模型以加快处理速度,而OnlyBasicScan 完全跳过ML以处理高质量的预处理图像。
输入
左侧为 PNG 产品标签,右侧为 JPEG 相机照片。示例演示了如何从这两类常见输入中读取二维码并识别其编码格式。

产品标签(PNG格式)

相机拍摄(JPEG)
using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
// Read from an image file with ML + classic scan (default)
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("product-label.png")));
foreach (QrResult result in results)
{
// Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}"); // QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}");
// Url is non-null only if Value is a valid URI
if (result.Url != null)
{
Console.WriteLine($"URI: {result.Url.AbsoluteUri}");
}
// Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected");
}
// Read from a bitmap with ML-only mode for faster throughput
var bitmap = AnyBitmap.FromFile("camera-capture.jpg");
var fastResults = reader.Read(new QrImageInput(bitmap, QrScanMode.OnlyDetectionModel));using IronQr;
using IronSoftware.Drawing;
using IronQr.Enum;
// Read from an image file with ML + classic scan (default)
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile("product-label.png")));
foreach (QrResult result in results)
{
// Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}"); // QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}");
// Url is non-null only if Value is a valid URI
if (result.Url != null)
{
Console.WriteLine($"URI: {result.Url.AbsoluteUri}");
}
// Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected");
}
// Read from a bitmap with ML-only mode for faster throughput
var bitmap = AnyBitmap.FromFile("camera-capture.jpg");
var fastResults = reader.Read(new QrImageInput(bitmap, QrScanMode.OnlyDetectionModel));Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
' Read from an image file with ML + classic scan (default)
Dim reader As New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("product-label.png")))
For Each result As QrResult In results
' Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}") ' QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}")
' Url is non-null only if Value is a valid URI
If result.Url IsNot Nothing Then
Console.WriteLine($"URI: {result.Url.AbsoluteUri}")
End If
' Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected")
Next
' Read from a bitmap with ML-only mode for faster throughput
Dim bitmap = AnyBitmap.FromFile("camera-capture.jpg")
Dim fastResults = reader.Read(New QrImageInput(bitmap, QrScanMode.OnlyDetectionModel))Imports IronQr
Imports IronSoftware.Drawing
Imports IronQr.Enum
' Read from an image file with ML + classic scan (default)
Dim reader As New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile("product-label.png")))
For Each result As QrResult In results
' Inspect the detected QR format
Console.WriteLine($"Format: {result.QrType}") ' QRCode, MicroQRCode, or RMQRCode
Console.WriteLine($"Value: {result.Value}")
' Url is non-null only if Value is a valid URI
If result.Url IsNot Nothing Then
Console.WriteLine($"URI: {result.Url.AbsoluteUri}")
End If
' Corner coordinates for positional context
Console.WriteLine($"Corners: {result.Points.Length} points detected")
Next
' Read from a bitmap with ML-only mode for faster throughput
Dim bitmap = AnyBitmap.FromFile("camera-capture.jpg")
Dim fastResults = reader.Read(New QrImageInput(bitmap, QrScanMode.OnlyDetectionModel))输出
控制台先显示产品标签二维码的编码格式、解码值、解析出的 URI 和角点数量,再显示相机照片的快速扫描结果数。

当应用要求使用特定格式时,可以检查 QrType 字段。例如,只生成标准二维码的仓库系统可以过滤掉微型二维码或矩形微型二维码的识别结果,因为这些结果可能来自噪声或无关标签。各格式的容量和形状有所不同:标准二维码最多可存储 7,089 个数字字符,微型二维码最多可存储 35 个数字字符,矩形微型二维码采用矩形布局,适用于空间有限的标签。
对二维码结果应用空值检查
QrReader.Read 未找到二维码时会返回空集合,始终不会返回 null。不过,仍需检查每个结果的属性。例如,Value 可能为空,解码后的字符串不是有效 URI 时,Url 会返回 null。
将数据传给其他系统之前,应检查三项内容:结果数量、解码值的完整性,以及类型或 URI 是否有效。
输入
这张纯白图像不含二维码,用于模拟一批混合文档中没有机器可读标签的页面。

using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
using System.Linq;
public static class QrValidator
{
public static List<QrResult> GetValidResults(
string imagePath,
QrEncoding? expectedFormat = null)
{
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile(imagePath)));
// Guard: no QR codes detected
if (!results.Any())
return new List<QrResult>();
return results
.Where(r => !string.IsNullOrWhiteSpace(r.Value))
.Where(r => expectedFormat == null || r.QrType == expectedFormat)
.ToList();
}
}
// Usage — only accept standard QR codes with non-empty values
var validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat: QrEncoding.QRCode);
if (validated.Count == 0)
{
Console.WriteLine("No valid QR codes found for processing.");
return;
}
foreach (var qr in validated)
{
// Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri);
}using IronQr;
using IronQr.Enum;
using IronSoftware.Drawing;
using System.Collections.Generic;
using System.Linq;
public static class QrValidator
{
public static List<QrResult> GetValidResults(
string imagePath,
QrEncoding? expectedFormat = null)
{
var reader = new QrReader();
IEnumerable<QrResult> results = reader.Read(new QrImageInput(AnyBitmap.FromFile(imagePath)));
// Guard: no QR codes detected
if (!results.Any())
return new List<QrResult>();
return results
.Where(r => !string.IsNullOrWhiteSpace(r.Value))
.Where(r => expectedFormat == null || r.QrType == expectedFormat)
.ToList();
}
}
// Usage — only accept standard QR codes with non-empty values
var validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat: QrEncoding.QRCode);
if (validated.Count == 0)
{
Console.WriteLine("No valid QR codes found for processing.");
return;
}
foreach (var qr in validated)
{
// Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri);
}Imports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Public Module QrValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedFormat As QrEncoding? = Nothing) As List(Of QrResult)
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile(imagePath)))
' Guard: no QR codes detected
If Not results.Any() Then
Return New List(Of QrResult)()
End If
Return results.
Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)).
Where(Function(r) expectedFormat Is Nothing OrElse r.QrType = expectedFormat).
ToList()
End Function
End Module
' Usage — only accept standard QR codes with non-empty values
Dim validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat:=QrEncoding.QRCode)
If validated.Count = 0 Then
Console.WriteLine("No valid QR codes found for processing.")
Return
End If
For Each qr In validated
' Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri)
Next qrImports IronQr
Imports IronQr.Enum
Imports IronSoftware.Drawing
Public Module QrValidator
Public Function GetValidResults(
imagePath As String,
Optional expectedFormat As QrEncoding? = Nothing) As List(Of QrResult)
Dim reader = New QrReader()
Dim results As IEnumerable(Of QrResult) = reader.Read(New QrImageInput(AnyBitmap.FromFile(imagePath)))
' Guard: no QR codes detected
If Not results.Any() Then
Return New List(Of QrResult)()
End If
Return results.
Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)).
Where(Function(r) expectedFormat Is Nothing OrElse r.QrType = expectedFormat).
ToList()
End Function
End Module
' Usage — only accept standard QR codes with non-empty values
Dim validated = QrValidator.GetValidResults(
"shipping-manifest.png",
expectedFormat:=QrEncoding.QRCode)
If validated.Count = 0 Then
Console.WriteLine("No valid QR codes found for processing.")
Return
End If
For Each qr In validated
' Safe for downstream: value is non-empty, format is verified
SendToInventoryApi(qr.Value, qr.Url?.AbsoluteUri)
Next qr输出
控制台显示验证器的输出:未检测到二维码,结果集合为空,因此没有数据传给下游处理流程。
没有有效结果时,验证器返回空列表,且始终不会返回 null,因此调用方无需检查返回值是否为 null。可选的 expectedFormat 参数用于筛选格式,使调用方只收到符合预期格式的结果。读取 Url 属性时,使用 null 条件运算符安全处理 URI 和非 URI 数据。
在异步工作流中,可以对 ReadAsync 使用相同的验证方式。等待调用完成后,对返回的集合执行同样的检查。
进一步阅读
- 纠错级别:生成二维码时如何提高抗损能力并配置纠错级别。
- 二维码读取方法:输入格式选项和读取方式。
- QrResult API 参考:完整的属性列表。
- 高级扫描示例:扫描模式配置。
准备部署到生产环境时,可查看许可选项。
点击此处下载完整的ChecksumFaultToleranceTest控制台应用程序项目。
常见问题
在C#中验证二维码校验和的重要性是什么?
验证二维码校验和对于确保二维码内编码数据的完整性至关重要。IronQR使用里德-所罗门错误校正自动解决解码过程中任何物理损坏,确保检索的数据准确可靠。
里德-所罗门错误校正在IronQR中如何工作?
IronQR中的里德-所罗门错误校正检测并修复特定级别的编码数据损坏。该校正级别可以是低、中、四分之一或高,确定解码过程中可以恢复的错误百分比。
如果无法使用IronQR解码二维码,我应该怎么办?
如果无法使用IronQR解码二维码,可能是由于损坏超过了错误校正能力。您可以尝试重新扫描代码,以更高的错误校正级别重新生成二维码,或检查输入图像质量是否可以改善。
IronQR能否处理不同的二维码编码格式?
可以,IronQR支持多种二维码编码格式,包括标准二维码、微型二维码和矩形微型二维码。扫描仪在读取过程中会自动检测格式,从而实现高效和灵活的二维码处理。
如果使用IronQR未检测到图像中的任何二维码,会发生什么?
如果使用IronQR未检测到任何二维码,QrReader.Read方法将返回一个空的集合。这表明解码失败,未找到可操作的二维码数据。
如何确保二维码数据符合我的应用程序要求?
解码后,您应该根据特定的应用程序要求验证解码值,例如检查期望的格式或验证内容是否非空并符合有效URI。
IronQR在二维码读取过程中是否提供格式意识?
是的,IronQR通过在读取过程中检测二维码格式提供格式意识。它将格式作为QrResult对象的一部分返回,允许您的应用程序适当处理特定格式。
IronQR中的`QrResult`类的作用是什么?
IronQR中的QrResult类代表二维码读取的解码结果。它提供了诸如解码值、检测到的二维码类型以及,如果值是有效URL,则可选的URI等属性。
IronQR如何处理二维码的物理损坏?
IronQR利用里德-所罗门错误校正在解码过程中自动校正二维码的轻微损坏,使其更能抵御物理损坏并确保数据完整性。
IronQR能否异步验证二维码?
可以,IronQR支持异步工作流。您可以使用ReadAsync以进行非阻塞的二维码读取,同时在结果上应用类似的验证模式。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。