IRONSOFTWAREHOME

如何在C#中处理条码操作的空检查

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

IronBarcode通过BarcodeResults集合的扫描结果。 如果输入图像无法识别,则此方法返回 null;如果未检测到条形码,则返回空集合。 如果输入为空、无效或格式无效,BarcodeWriter.CreateBarcode将抛出异常。

现实世界中的扫描源,例如摄像头画面、文档上传和仓库扫描仪,可能并不总是能提供可读的条形码。 在不检查为空或无效值的情况下访问结果属性或迭代集合会导致在运行时ArgumentException。 在读取和写入操作中使用保护子句有助于防止生产环境中出现这些异常。

本操作指南解释了如何通过使用保护条款、信任过滤和可重用验证器模式来处理IronBarcode读写操作中的null和空结果。


快速开始:处理条码操作中的空结果

使用IronBarcode的保护模式在访问任何结果属性之前安全地检查BarcodeResults集合。 立即阅读并查看以下简要内容,开始学习:

  1. 1Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. 2复制并运行这段代码。

    using IronBarCode;
    
    BarcodeResults results = BarcodeReader.Read("label.png");
    
    // Guard: null or empty
    if (results is null || results.Count == 0)
    {
        Console.WriteLine("No barcodes detected.");
        return;
    }
    
    Console.WriteLine(results.First().Value);
    C#
  3. 3部署到您的生产环境中进行测试

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

如何处理条码结果的空和空结果?

有两种故障模式:如果输入不是有效图像,则BarcodeResults为null;如果图像不包含条码,则为空。 访问Value或迭代而不验证两个条件会导致运行时异常。

进入处理循环前,请检查以下两个条件:

输入

一个Code128条码运输标签(成功路径)和一个不包含条码的空白图像(失败路径)。

编码 SHP-20240001 的 Code128 条形码,用作运输标签的输入

shipping-label.png(成功路径)

用于触发空结果路径的无条形码空白图像

blank-image.png(失败路径,无条形码)

using IronBarCode;

// BarcodeReader.Read() returns a BarcodeResults collection, not a single result
BarcodeResults results = BarcodeReader.Read("shipping-label.png");

// Null check: image was not recognized as a valid image source
// Empty check: image was valid but contained no detectable barcodes
if (results is null || results.Count == 0)
{
    // Log, return a default, or throw a domain-specific exception
    Console.WriteLine("No barcodes found in the input image.");
    return;
}

// Collection is safe to iterate; each BarcodeResult holds one decoded barcode
foreach (BarcodeResult result in results)
{
    // Guard individual result properties; partial scans or severely
    // damaged barcodes can produce results where .Value is empty or whitespace
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    // BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}

每个Text字符串属性,两者都返回解码的条码内容。 条形码严重损坏或扫描不完整可能会产生空白值或空格值。 在每个结果上使用string.IsNullOrWhiteSpace,以防止空值到达下游系统。

ConfidenceThreshold属性(0.0到1.0),该属性在它们达到结果集合之前删除低质量读取:

using IronBarCode;

// ConfidenceThreshold filters low-quality reads before they enter the
// BarcodeResults collection. Reads below the threshold are discarded
// during scanning, not after, so no post-filtering of the collection is needed.
var options = new BarcodeReaderOptions
{
    ConfidenceThreshold = 0.7  // range 0.0 to 1.0; lower values accept weaker signals
};

BarcodeResults results = BarcodeReader.Read("shipping-label.png", options);

// Still check for null and empty even with a threshold applied;
// an image with no barcodes returns an empty collection, not null
if (results is null || results.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}

foreach (var result in results)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");

如何将空安全模式应用于条码写入?

BarcodeEncoding枚举。 传递 null 值或空字符串会立即抛出异常。 格式限制也适用:Code 128有字符限制。 在调用之前验证输入可以避免这些异常情况进入编码步骤:

using IronBarCode;

// Input may arrive from user input, a database, or an API response
string inputValue = GetValueFromUserOrDatabase(); // Could be null

// Guard: null, empty, or whitespace input cannot produce a valid barcode
if (string.IsNullOrWhiteSpace(inputValue))
{
    Console.WriteLine("Cannot generate barcode: input value is null or empty.");
    return;
}

// Guard: format-specific constraints must be satisfied before encoding
// EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
BarcodeWriterEncoding encoding = BarcodeWriterEncoding.EAN8;
if (encoding == BarcodeWriterEncoding.EAN8 && !System.Text.RegularExpressions.Regex.IsMatch(inputValue, @"^\d{7,8}$"))
{
    Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.");
    return;
}

// Input is validated; CreateBarcode will not throw for null or format mismatch
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");

输出

一个有效的7位数字输入(EAN-8条码。 空值、空值或非数字输入会被保护子句捕获,永远不会到达编码步骤。

根据有效的7位输入码1234567生成的EAN-8条形码

写入 API 也会进行内部验证:它会检查校验和、验证长度限制,并拒绝所选编码的无效字符。 上述的保护条款可以及早发现问题,使调用者能够控制错误消息和恢复路径。 有关支持的编码及其约束的完整列表,请参阅条码创建指南从数据创建条码指南


如何在下游处理之前验证结果?

当条形码数据被导入到另一个系统(数据库写入、API 调用、标签打印机)时,最好在传递数据之前,将结果计数、值完整性和类型检查整合到一个可重用的方法中:

输入

一个Code128条码仓库扫描用作验证器的读取目标。

Code128 条形码编码 WH-SCAN-4471 用作验证器示例中的仓库扫描输入
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

// Reusable validation helper — consolidates null, empty, value, and
// expected-format checks into a single method. Returns an empty list
// (never null) so callers do not need to null-check the return value.
public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double confidenceThreshold = 0.7)
    {
        // Apply confidence threshold at scan level via BarcodeReaderOptions
        var options = new BarcodeReaderOptions
        {
            ConfidenceThreshold = confidenceThreshold
        };

        BarcodeResults results = BarcodeReader.Read(imagePath, options);

        // Return empty list instead of null so callers never need to null-check the return value
        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))           // skip results with empty decoded data
            .Where(r => expectedType == null || r.BarcodeType == expectedType) // null accepts any symbology
            .ToList();
    }
}

// Usage: pass the image path and the symbology you expect
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    confidenceThreshold: 0.7);

if (validated.Count == 0)
{
    // No valid results; log the failure and skip downstream processing
    return;
}

// All results have passed null, empty, type, and confidence checks
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call
}

该方法返回空列表而不是 null,因此调用者永远不需要检查返回值是否为 null。 可选的Code 128时接收到意外格式。

对于跨多个文件的批量读取,对每个文件应用相同的模式并汇总结果。 BarcodeReaderOptions上预先将扫描范围缩小到预期的符号,以便更少的不需要的结果到达验证器。


进一步阅读

-条形码读取教程:扫描配置和读取选项。

当管道准备就绪投入生产时,请查看许可选项

常见问题解答

BarCode操作中的空值检查是什么?

BarCode操作中的空值检查是指验证BarCode结果或输入是否为空,以防止运行时错误并确保BarCode处理顺畅。

在 C# BarCode 操作中,为什么空值检查很重要?

在 C# BARCODE 操作中,空值检查至关重要,它能避免异常,并确保应用程序在 BARCODE 数据缺失或无效时能够优雅地处理这些情况。

IronBarcode 如何协助进行空值检查?

IronBarcode 提供了内置方法,可轻松处理空值检查,使开发人员无需手动实现复杂的验证逻辑,即可安全地管理 BarCode 数据。

在 IronBarcode 中进行空值检查有哪些最佳实践?

最佳实践包括检查 BarCodeResults 是否为空值、在处理前验证输入数据,以及使用置信度过滤器来确保 BarCode 扫描结果的可靠性。

IronBarcode 能否根据置信度过滤结果以避免空输出?

是的,IronBarcode 支持按置信度级别过滤 BarCode 识别结果,这有助于减少空结果,并确保 BarCode 读取的高准确性。

是否有办法使用 IronBarcode 验证输入内容?

IronBarcode 支持对写入数据进行验证,以确保编码到 BarCode 中的数据正确且完整,从而避免 BarCode 生成过程中的问题。

如果未处理空BarCode结果会发生什么?

如果未处理BarCode结果为空的情况,可能会导致运行时异常并中断应用程序的流程,从而引发潜在的崩溃或操作错误。

How does IronBarcode's reusable validator pattern work?

IronBarcode's reusable validator pattern consolidates null checks, empty checks, value integrity, and expected format validation into a single method, simplifying the validation process before results are used downstream.

What are some constraints that BarcodeWriterEncoding handles during barcode creation?

BarcodeWriterEncoding imposes constraints like string length and character validity based on the barcode type. For example, EAN-8 must have 7 or 8 numeric digits. Correctly formatted input avoids exceptions during encoding.

How does IronBarcode ensure the quality of scanned barcodes?

IronBarcode uses properties such as ConfidenceThreshold in BarcodeReaderOptions to ensure only high-quality barcodes are included in results. This pre-scanning filter means low-quality reads are discarded before further processing.

Curtis Chau
技术作家

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

...
阅读更多

准备开始了吗?

Nuget Downloads 2,422,100版本:2026.9刚刚发布

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

版本: 2026.9

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

版本: 2026.9

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