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

This article was translated from English: Does it need improvement?
Translated
View the article in English

BarcodeReader.Read()BarcodeResults 컬렉션을 반환합니다 — 단일 값이 아닙니다. 입력 이미지가 인식되지 않으면 컬렉션은 null일 수 있으며, 바코드를 찾지 못하면 비어 있을 수 있습니다. 쓰기 측면에서, BarcodeWriter.CreateBarcode()는 null 또는 유효하지 않은 입력이 전달될 때 예외를 발생시킵니다. 결과 속성에 접근하거나 출력을 생성하기 전에 두 경로 모두 보호 구문이 필요합니다.

이 가이드는 IronBarcode 읽기 및 쓰기 작업의 null 및 빈 결과 처리를 다루며, NullReferenceExceptionArgumentException가 프로덕션에 도달하지 못하게 하는 방어 패턴을 제공합니다.

빠른 시작: 바코드 작업에서 널 결과 처리

런타임 예외를 방지하기 위해 어떤 결과 속성에도 접근하기 전에 BarcodeResults 컬렉션을 null 및 빈 상태 모두에 대해 검사하세요.

  1. NuGet 패키지 관리자를 사용하여 https://www.nuget.org/packages/BarCode 설치하기

    PM > Install-Package BarCode
  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);
  3. 실제 운영 환경에서 테스트할 수 있도록 배포하세요.

    무료 체험판으로 오늘 프로젝트에서 IronBarcode 사용 시작하기

    arrow pointer

널 및 빈 바코드 결과를 처리하는 방법?

BarcodeReader.Read()BarcodeResults를 반환하며, 이는 BarcodeResult 객체의 컬렉션입니다. 보호해야 하는 두 가지 실패 모드가 있습니다: 컬렉션 자체가 null인 경우(입력이 유효한 이미지로 인식되지 않음)와 컬렉션이 비어 있는 경우(유효한 이미지이나 바코드가 발견되지 않음). 조건을 확인하지 않고 .First(), .Value에 접근하거나 반복을 시도하면 런타임 예외가 발생합니다.

표준 보호 패턴은 처리 루프에 진입하기 전에 두 조건을 확인합니다:

using IronBarCode;

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

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
using IronBarCode;

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

// Null check: image may not be recognized
// Empty check: image recognized but no barcodes found
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;
}

foreach (BarcodeResult result in results)
{
    // Guard individual result properties
    if (string.IsNullOrWhiteSpace(result.Value))
    {
        Console.WriteLine($"Empty value detected for {result.BarcodeType}");
        continue;
    }

    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}");
}
$vbLabelText   $csharpLabel

BarcodeResult는 문자열 속성으로 .Value.Text를 노출하며, 둘 다 디코딩된 바코드 내용을 반환합니다. 정상 운영에서는 이러한 값이 채워지지만, 매우 손상된 바코드, 부분 스캔 또는 저신뢰도 감지 같은 엣지 케이스가 존재하여 값이 비어 있거나 공백일 수 있습니다. 개별 결과에 대한 string.IsNullOrWhiteSpace() 확인으로 데이터가 전파되기 전에 이러한 경우를 잡을 수 있습니다.

.Confidence 속성(0.0과 1.0 사이의 double)은 추가 품질 신호를 제공합니다. 프로덕션 시스템의 경우, null 체크와 신뢰도 임계값을 결합할 수 있습니다:

double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
double minimumConfidence = 0.7;

var validResults = results
    .Where(r => !string.IsNullOrWhiteSpace(r.Value) && r.Confidence >= minimumConfidence)
    .ToList();

if (validResults.Count == 0)
{
    Console.WriteLine("No barcodes met the confidence threshold.");
    return;
}
$vbLabelText   $csharpLabel

BarcodeReaderOptions 클래스는 또한 스캔 레벨에서 필터링하는 MinimumConfidence 속성을 제공합니다. 옵션 객체에서 이 설정은 고수율 배치 스캔 시나리오에 더 깔끔합니다.

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

BarcodeWriter.CreateBarcode()는 문자열 값과 BarcodeWriterEncoding 또는 BarcodeEncoding 열거형을 허용합니다. 널 또는 빈 문자열을 전달하면 예외가 발생합니다. 또한, 형식 별 제약 조건이 적용됩니다 — EAN-8은 정확히 7–8개의 숫자 자릿수가 필요하며, UPC-A는 11–12개의 자릿수가 필요하고, Code 128은 최대 문자 제한이 있습니다. 이 제약 조건을 위반하면 예외가 발생합니다.

방어 패턴은 CreateBarcode()를 호출하기 전에 입력을 검증합니다:

using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

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

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
using IronBarCode;

string inputValue = GetValueFromUserOrDatabase(); // Could be null

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

// Guard: format-specific constraints (example: EAN-8 requires 7-8 digits)
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;
}

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);
barcode.SaveAsPng("output-barcode.png");
$vbLabelText   $csharpLabel

IronBarcode의 쓰기 API는 자체 내부 검증을 수행합니다 — 체크섬을 확인하고, 길이 제한을 검증하며, 선택한 인코딩에 대해 유효하지 않은 문자를 거부합니다. 이러한 검사들은 설명이 포함된 메시지와 함께 System.Exception 예외를 발생시킵니다. 위에 언급된 보호 구문은 라이브러리에 도달하기 전에 문제를 잡아내며, 이를 통해 오류 메시징 및 흐름을 제어할 수 있습니다. 지원되는 인코딩 및 제약 조건의 전체 목록은 바코드 생성 방법데이터에서 바코드 생성 가이드를 참조하세요.

후속 처리 전 결과를 검증하는 방법?

바코드 데이터가 다른 시스템으로 피드될 때 — 데이터베이스 기록, API 호출, 라벨 프린터 — 우리는 결과 수, 개별 값의 무결성, 바코드 유형을 전달 전에 체크하는 검증 게이트가 필요합니다. 이것은 널 체크 로직을 단일 재사용 가능 메서드로 통합합니다.

using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

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

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
using IronBarCode;
using System.Collections.Generic;
using System.Linq;

public static class BarcodeValidator
{
    public static List<BarcodeResult> GetValidResults(
        string imagePath,
        BarcodeEncoding? expectedType = null,
        double minimumConfidence = 0.7)
    {
        BarcodeResults results = BarcodeReader.Read(imagePath);

        if (results is null || results.Count == 0)
            return new List<BarcodeResult>();

        return results
            .Where(r => !string.IsNullOrWhiteSpace(r.Value))
            .Where(r => r.Confidence >= minimumConfidence)
            .Where(r => expectedType == null || r.BarcodeType == expectedType)
            .ToList();
    }
}

// Usage
var validated = BarcodeValidator.GetValidResults(
    "warehouse-scan.png",
    expectedType: BarcodeEncoding.Code128,
    minimumConfidence: 0.85);

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

// Safe to pass to downstream systems
foreach (var barcode in validated)
{
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString());
}
$vbLabelText   $csharpLabel

검증자 메서드는 null이 아닌 빈 목록을 반환합니다 — 이는 호출자가 반환 값을 널 체크할 필요성을 없애며, 이는 표준 방어 패턴입니다. 옵션 expectedType 매개변수는 다운스트림 시스템이 예상하는 바코드 형식만을 받도록 보장하여, 하나의 이미지에서 QR 코드와 코드 128을 모두 얻었을 때의 불일치를 방지합니다.

다수의 파일에 걸친 배치 읽기의 경우, 동일한 패턴을 파일별로 적용하고 결과를 집계합니다. BarcodeReaderOptions 클래스는 스캔 레벨에서 필터링하는 ExpectBarcodeTypes를 지원하여, 검증 전에 노이즈를 줄입니다.

다음 단계

IronBarcode 작업에서 null 검사는 두 가지 패턴으로 요약됩니다: 속성을 읽기 전에 BarcodeResults 컬렉션(null + 빈 값)을 보호하고, 쓰기 전에 입력 문자열을 검증합니다. 위의 재사용 가능한 유효성 검사기는 두 가지 문제를 중앙에 배치합니다.

더 깊은 내용을 위해 스캔 설정에 관한 바코드 읽기 튜토리얼과 모든 BarcodeResult 속성에 대한 출력 데이터 형식 가이드, 그리고 완전한 유형 표면에 대한 API 참조를 탐색해 보세요.

무료 30일 체험판 시작하기를 통해 이러한 패턴을 실제 스캔 데이터와 비교해 테스트해 보세요. 준비가 되면 라이선스 옵션 보기를 누르면 $499부터 시작합니다.

자주 묻는 질문

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

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

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

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

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

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

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

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

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

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

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

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

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

null 바코드 결과를 처리하지 않으면 런타임 예외가 발생할 수 있으며, 이는 애플리케이션의 흐름을 방해하여 잠재적인 충돌이나 잘못된 동작을 야기할 수 있습니다.

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/how-to/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Howto.php
Line: 31
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

시작할 준비 되셨나요?
Nuget 다운로드 2,108,094 | 버전: 2026.3 방금 출시되었습니다
Still Scrolling Icon

아직도 스크롤하고 계신가요?

빠른 증거를 원하시나요? PM > Install-Package BarCode
샘플을 실행하세요 실이 바코드로 변하는 모습을 지켜보세요.