IRONSOFTWAREHOME

バーコード操作におけるNullチェックをC#で処理する方法

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

IronBarcodeは、BarcodeResultsコレクションとして返します。 このメソッドは、入力画像が認識されない場合は null を返し、バーコードが検出されない場合は空のコレクションを返します。 入力がnull、空、または無効な形式の場合、BarcodeWriter.CreateBarcodeが例外をスローします。

カメラ映像、文書アップロード、倉庫のスキャナーなど、実際のスキャン元では、必ずしも読み取り可能なバーコードが得られるとは限りません。 結果のプロパティーにアクセスするか、変数にイテレーションしてもnullまたは空の値を確認しないと、実行時にNullReferenceExceptionが発生する可能性があります。無効な文字列をwrite APIに渡すと、ArgumentExceptionが発生する可能性があります。 読み取り操作と書き込み操作の両方でガード句を使用することで、本番環境でこれらの例外が発生するのを防ぐことができます。

このハウツーでは、IronBarcodeの読み取りおよび書き込み操作でguard句、信頼度フィルタリング、再利用可能なバリデータパターンを使用してnullおよび空の結果を処理する方法を説明します。


クイックスタート: バーコード操作で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

Nullおよび空のバーコード結果をどのように処理しますか?

失敗モードは2つあります。入力が有効な画像でない場合、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}");

バーコード書き込みにNullセーフパターンを適用する方法

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処理におけるNullチェックとは、実行時エラーを防ぎ、BarCode処理を円滑に行うために、BarCodeの結果や入力がNullかどうかを確認することです。

C#でのBarCode処理において、nullチェックが重要な理由は何ですか?

C#でのBarCode処理において、例外を回避し、BarCodeデータが欠落または無効である場合にアプリケーションが適切に処理できるようにするためには、Nullチェックが不可欠です。

IronBarcodeは、nullチェックにおいてどのように役立ちますか?

IronBarcodeには、nullチェックを簡単に処理するための組み込みメソッドが用意されており、開発者は複雑な検証ロジックを手動で実装することなく、BarCodeデータを安全に管理できます。

IronBarcode における null チェックのベストプラクティスにはどのようなものがありますか?

ベストプラクティスとしては、BarCodeResultsのnull値チェック、処理前の入力検証、信頼性の高いバーコードスキャン結果を確保するための信頼度フィルターの使用などが挙げられます。

IronBarcodeは、NULL出力となるのを防ぐために、信頼度に基づいて結果をフィルタリングできますか?

はい、IronBarcodeでは信頼度レベルに基づいてBARCODE検索結果をフィルタリングすることが可能です。これにより、無効な出力を減らし、BARCODE読み取りの高い精度を確保できます。

IronBarcodeを使用して入力データを検証する方法はありますか?

IronBarcode を使用すると、入力データの検証が可能になり、BarCode にエンコードされるデータが正確かつ完全であることを確認できるため、BarCode 生成時の問題を未然に防ぐことができます。

BarCodeの結果がnullの場合、適切に処理されないとどうなるでしょうか?

BARCODEの結果が null である場合の処理が行われないと、実行時例外が発生し、アプリケーションの処理フローが中断される可能性があります。その結果、クラッシュや誤動作を引き起こす恐れがあります。

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に精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

...
詳しく読む

準備はできましたか?

Nuget Downloads 2,422,100バージョン:2026.9リリースされたばかり

あなたの無料30日間の試用キーをすぐに入手。
クレジットカードやアカウントの作成は不要です。
PDF用C# 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のソリューションエクスプローラーで、Referencesを右クリックします。 "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

世界中の数百万人のエンジニアから信頼されています。

ライセンスはより安く
義務のない相談を受ける
下記のフォームを記入するか、sales@ironsoftware.comにメールしてください。
あなたの詳細は常に守秘されます。
世界中の数百万人のエンジニアから信頼されています。
ライセンスはより安く
あなたの無料30日間の試用キーをすぐに入手。
クレジットカードやアカウントの作成は不要です。