IRONSOFTWAREHOME

C#에서 바코드 작업을 위한 널 체크 처리 방법

Curtis Chau
Curtis Chau
Updated: 2026년 5월 9일

IronBarcode는 C#에서 BarcodeReader.Read을 통해 BarcodeResults 컬렉션으로 스캔 결과를 반환합니다. 이 메서드는 입력 이미지를 인식할 수 없는 경우 null을 반환하고, 바코드가 감지되지 않은 경우 빈 컬렉션을 반환합니다. 입력이 null, 비어 있거나 잘못된 형식인 경우 BarcodeWriter.CreateBarcode는 예외를 던집니다.

카메라 영상, 문서 업로드, 창고 스캐너와 같은 실제 스캔 소스는 항상 판독 가능한 바코드를 제공하지 않을 수 있습니다. 결과 속성에 액세스하거나 컬렉션을 반복할 때 null 또는 빈 값을 확인하지 않으면 런타임 시 NullReferenceException가 발생할 수 있습니다. 잘못된 문자열을 쓰기 API로 전달하면 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이고, 이미지에 바코드가 포함되어 있지 않으면 비어 있습니다. 두 조건을 모두 확인하지 않고 First, 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}");
}

BarcodeResultValueText 문자열 속성을 제공하며, 둘 다 디코딩된 바코드 콘텐츠를 반환합니다. 바코드가 심하게 손상되었거나 스캔이 부분적으로만 이루어진 경우, 값이 비어 있거나 공백으로 표시될 수 있습니다. 각 결과에서 빈 값이 하류 시스템에 도달하지 않도록 string.IsNullOrWhiteSpace을 사용하세요.

BarcodeReaderOptions에도 (0.0에서 1.0까지의) ConfidenceThreshold 속성이 있으며, 결과 컬렉션에 도달하기 전에 저품질 판독값을 제거합니다:

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}");

바코드 쓰기에 널 안전 패턴을 적용하는 방법?

BarcodeWriter.CreateBarcode은 문자열 값과 BarcodeWriterEncoding 또는 BarcodeEncoding 열거형을 수용합니다. null 또는 빈 문자열을 전달하면 즉시 예외가 발생합니다. 형식 제약도 적용: EAN-8는 78자리의 숫자만을 수용하고, UPC-A는 1112자리를, 그리고 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자리 입력(1234567)은 스캔 가능한 EAN-8 바코드를 생성합니다. null, 빈 값 또는 숫자가 아닌 입력은 가드 절에 의해 포착되어 인코딩 단계에 도달하지 않습니다.

유효한 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 검사를 할 필요가 없습니다. 옵션 expectedType 매개변수는 심볼로지에 따라 필터링하여 동일한 이미지에서 QR 코드와 Code 128를 모두 스캔할 때 하류 시스템이 예상하지 않는 형식을 받지 않도록 합니다.

여러 파일을 일괄 적으로 읽으 려면 파일마다 동일한 패턴을 적용하고 결과를 집계하십시오. ExpectBarcodeTypes 옵션은 BarcodeReaderOptions에서 예상되는 심볼로지로 스캔을 좁혀서 원치 않는 결과가 검사기에 도달하지 않도록 합니다.


추가 자료

파이프라인이 프로덕션 단계에 진입하면 라이선스 옵션을 확인하세요 .

자주 묻는 질문

바코드 작업에서 null 체크란 무엇인가요?

바코드 작업에서 null 체크는 바코드 결과나 입력이 null인지 확인하여 런타임 오류를 방지하고 원활한 바코드 처리를 보장하는 것입니다.

C# 바코드 작업에서 null 체크가 중요한 이유는 무엇인가요?

C# 바코드 작업에서 null 체크는 예외를 피하고 바코드 데이터가 없거나 잘못된 경우를 매끄럽게 처리할 수 있도록 보장하는 데 필수적입니다.

IronBarcode는 null 체크에 어떻게 도움을 주나요?

IronBarcode는 내장된 메소드를 제공하여 복잡한 유효성 검사 로직을 수동으로 구현하지 않고도 개발자가 바코드 데이터를 안전하게 관리할 수 있게 합니다.

IronBarcode에서 null 체크를 위한 몇 가지 모범 사례는 무엇인가요?

모범 사례에는 바코드 결과에서 null 값을 확인하고 처리를 시작하기 전에 입력을 검증하며, 신뢰도 필터를 사용하여 신뢰할 수 있는 바코드 스캔 결과를 보장하는 것이 포함됩니다.

IronBarcode가 신뢰도로 결과를 필터링하여 null 출력을 방지할 수 있나요?

네, IronBarcode는 바코드 결과를 신뢰도 수준에 따라 필터링할 수 있게 하여 null 출력을 줄이고 바코드 읽기의 높은 정확성을 보장합니다.

IronBarcode를 사용하여 입력을 기록하기 위한 유효성 검사가 가능한가요?

IronBarcode는 바코드에 인코딩되는 데이터가 올바르고 완전한지 확인하여 바코드 생성 시의 문제를 방지하기 위해 입력의 유효성을 검사할 수 있게 합니다.

null 바코드 결과를 처리하지 않으면 어떻게 되나요?

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
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

...
더 읽어보기

시작할 준비 되셨나요?

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 솔루션 탐색기에서 참조를 마우스 오른쪽 버튼으로 클릭합니다. 찾아보기를 선택하고 "IronBarCode.dll"을 선택합니다.

라이선스 가격은 749달러 부터 시작합니다.

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일 무료 체험판 키를 받으세요.
신용카드나 계정 생성은 필요하지 않습니다.