Barcode İşlemlerinde Null Kontrolü Nasıl Yapılır - C

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

IronBarcode, tarama sonuçlarını C# içinde BarcodeReader.Read yoluyla bir BarcodeResults koleksiyonu olarak döndürür. Eğer giriş resmi tanınmazsa bu yöntem null, barkod tespit edilmezse boş bir koleksiyon döndürür. Eğer giriş null, boş veya geçersiz bir formatta ise BarcodeWriter.CreateBarcode bir istisna fırlatır.

Kamera beslemeleri, belge yüklemeleri ve depo tarayıcıları gibi gerçek dünya tarama kaynakları her zaman okunabilir bir barkod sağlamayabilir. Sonuç özelliklerine erişmek veya null ya da boş değerleri kontrol etmeden koleksiyonu döngüye almak, çalışma zamanında bir NullReferenceException neden olabilir. Geçersiz stringleri yazma API'sine geçirirseniz bir ArgumentException oluşabilir. Hem okuma hem de yazma işlemlerinde koruyucu şartlar kullanmak, bu istisnaları üretimde önlemeye yardımcı olur.

Bu nasıl yapılır, IronBarcode'da okuma ve yazma işlemlerinde null ve boş sonuçlarla başa çıkmanın koruyucu cümleler, güven filtresi ve yeniden kullanılabilir doğrulayıcı deseni kullanarak nasıl yapılacağını açıklar.


Hızlı Başlangıç: Barkod İşlemlerinde Null Sonuçlarla Baş Etmek

IronBarcode'ın koruma desenini kullanarak herhangi bir sonuç özelliğine erişmeden önce BarcodeResults koleksiyonunu güvenli bir şekilde kontrol edin. Bu minimal okuma ve kontrol ile hemen başlayın:

  1. NuGet Paket Yöneticisi ile https://www.nuget.org/packages/BarCode yükleyin

    PM > Install-Package BarCode
  2. Bu kod parçasını kopyalayıp çalıştırın.

    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. Canlı ortamınızda test etmek için dağıtın

    Bugün projenizde IronBarcode kullanmaya başlayın ücretsiz deneme ile

    arrow pointer

Null ve Boş Barkod Sonuçları Nasıl İşlenir?

İki başarısızlık modu vardır: Eğer giriş geçerli bir resim değilse BarcodeResults null olur ve resim herhangi bir barkod içermiyorsa boştur. First, Value, veya her iki durumu kontrol etmeden döngüye almak çalışma zamanı istisnasına neden olur.

İşlem döngüsüne girmeden önce her iki durumu kontrol edin:

Girdi

Bir Code128 barkod sevkıyat etiketi (başarı yolu) ve hiç barkod içermeyen boş bir görüntü (başarısızlık yolu).

Code128 barcode encoding SHP-20240001 used as the shipping label input

shipping-label.png (başarı yolu)

Blank white image with no barcode used to trigger the empty result path

blank-image.png (başarısızlık yolu, barkod yok)

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-guard.cs
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}");
}
Imports IronBarCode

' BarcodeReader.Read() returns a BarcodeResults collection, not a single result
Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
    ' Log, return a default, or throw a domain-specific exception
    Console.WriteLine("No barcodes found in the input image.")
    Return
End If

' Collection is safe to iterate; each BarcodeResult holds one decoded barcode
For Each result As BarcodeResult 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) Then
        Console.WriteLine($"Empty value detected for {result.BarcodeType}")
        Continue For
    End If

    ' BarcodeType identifies the symbology (Code128, QRCode, EAN8, etc.)
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
$vbLabelText   $csharpLabel

Her BarcodeResult, decoded barcode içeriğini döndüren Value ve Text string özelliklerine sahiptir. Ağır hasarlı barkodlar veya kısmi taramalar boş veya yalnızca boşluk içeren değerler üretebilir. Boş değerlerin alt sistemlere ulaşmasını önlemek için her sonuç üzerinde string.IsNullOrWhiteSpace kullanın.

BarcodeReaderOptions ayrıca, sonuçlar koleksiyonuna ulaşmadan önce düşük kaliteli okumalara filtre uygulayan (0.0 ila 1.0 arası) bir ConfidenceThreshold özelliğine sahiptir:

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/confidence-filter.cs
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}");
Imports 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.
Dim options As New BarcodeReaderOptions With {
    .ConfidenceThreshold = 0.7  ' range 0.0 to 1.0; lower values accept weaker signals
}

Dim results As BarcodeResults = 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 Nothing OrElse results.Count = 0 Then
    Console.WriteLine("No barcodes met the confidence threshold.")
    Return
End If

For Each result In results
    Console.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")
Next
$vbLabelText   $csharpLabel

Null-Güvenli Şablonlar Barkod Yazmaya Nasıl Uygulanır?

BarcodeWriter.CreateBarcode bir string değeri ve bir BarcodeWriterEncoding veya BarcodeEncoding enum alır. Null veya boş bir dizin geçirmek anında bir istisna fırlatır. Biçim kısıtlamaları da geçerlidir: EAN-8, 7 ila 8 sayısal basamak kabul eder, UPC-A 11 ila 12 kabul eder ve Code 128'in bir karakter sınırı vardır. Çağrıdan önce girişi doğrulamak, bu istisnaların kodlama adımında ortaya çıkmasını engeller:

:path=/static-assets/barcode/content-code-examples/how-to/null-checking/null-safe-write.cs
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");
Imports IronBarCode

' Input may arrive from user input, a database, or an API response
Dim inputValue As String = GetValueFromUserOrDatabase() ' Could be Nothing

' Guard: null, empty, or whitespace input cannot produce a valid barcode
If String.IsNullOrWhiteSpace(inputValue) Then
    Console.WriteLine("Cannot generate barcode: input value is null or empty.")
    Return
End If

' Guard: format-specific constraints must be satisfied before encoding
' EAN-8 accepts exactly 7 or 8 numeric digits (the 8th is the check digit)
Dim encoding As BarcodeWriterEncoding = BarcodeWriterEncoding.EAN8
If encoding = BarcodeWriterEncoding.EAN8 AndAlso Not System.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") Then
    Console.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.")
    Return
End If

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

Çıktı

Geçerli bir 7 haneli giriş (1234567) taranabilir bir EAN-8 barkodu üretir. Null, boş veya sayısal olmayan girişler koruyucu şartlar tarafından yakalanır ve asla kodlama aşamasına ulaşmaz.

Geçerli 7 basamaklı giriş 1234567'ten oluşturulan EAN-8 barkod

Yazma API'si de kendi iç doğrulamasını yapar: kontrol toplamlarını kontrol eder, uzunluk kısıtlamalarını doğrular ve seçilmiş kodlama için geçersiz karakterleri reddeder. Yukarıdaki koruyucu şartlar, sorunları daha önce yakalar, böylece çağrıcı hata mesajı ve kurtarma yolu üzerinde kontrol sahibi olur. Desteklenen tüm kodlama ve kısıtlamalarının tam listesini görmek için barkod oluşturma nasıl yapılır ve veriden barkod oluşturma kılavuzuna bakın.


Sonuçları Aşağı Akış İşleminden Önce Nasıl Doğrularım?

Barkod verileri başka bir sisteme (veritabanı yazma, API çağrısı, etiket yazıcı) beslenirken, veri aktarmadan önce sonuç sayısını, değer bütünlüğünü ve tür kontrollerini tek bir yeniden kullanılabilir yönteme konsolide etmek faydalı olabilir.

Girdi

Bir depo tarama hedefi olarak kullanılan bir Code128 barkod depo taraması.

Doğrulayıcı örneği için depo tarama girdisi olarak WH-SCAN-4471 kodlaması
:path=/static-assets/barcode/content-code-examples/how-to/null-checking/barcode-validator.cs
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
}
Imports IronBarCode
Imports System.Collections.Generic
Imports 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 Module BarcodeValidator
    Public Function GetValidResults(
        imagePath As String,
        Optional expectedType As BarcodeEncoding? = Nothing,
        Optional confidenceThreshold As Double = 0.7) As List(Of BarcodeResult)

        ' Apply confidence threshold at scan level via BarcodeReaderOptions
        Dim options As New BarcodeReaderOptions With {
            .ConfidenceThreshold = confidenceThreshold
        }

        Dim results As BarcodeResults = BarcodeReader.Read(imagePath, options)

        ' Return empty list instead of null so callers never need to null-check the return value
        If results Is Nothing OrElse results.Count = 0 Then
            Return New List(Of BarcodeResult)()
        End If

        Return results _
            .Where(Function(r) Not String.IsNullOrWhiteSpace(r.Value)) _          ' skip results with empty decoded data
            .Where(Function(r) expectedType Is Nothing OrElse r.BarcodeType = expectedType) _ ' null accepts any symbology
            .ToList()
    End Function
End Module

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

If validated.Count = 0 Then
    ' No valid results; log the failure and skip downstream processing
    Return
End If

' All results have passed null, empty, type, and confidence checks
For Each barcode In validated
    SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream call
Next barcode
$vbLabelText   $csharpLabel

Yöntem, null değerine geri dönmeyecek şekilde boş bir liste döndürür. Opsiyonel expectedType parametresi, bir tarama aynı resimden hem bir QR kodu hem de bir Kod 128 aldığında beklenmeyen formatların alt sisteme ulaşmasını önleyen sembolojiye göre filtre uygular.

Birden fazla dosyada toplu okuma için, her dosya için aynı deseni uygulayın ve sonuçları birleştirin. BarcodeReaderOptions üzerindeki ExpectBarcodeTypes seçeneği taramayı önceden beklenen sembolojilere daraltır, böylece daha az istenmeyen sonuç doğrulayıcıya ulaşır.


Daha Fazla Okuma

Lisanslama seçeneklerini görün boru hattı üretime hazır olduğunda.

Sıkça Sorulan Sorular

Barkod işlemlerinde null kontrolü nedir?

Barkod işlemlerinde null kontrolü, çalışma zamanı hatalarını önlemek ve sorunsuz barkod işleme sağlamak için bir barkod sonucu veya girişinin null olup olmadığını doğrulamayı içerir.

C# barkod işlemlerinde null kontrolü neden önemlidir?

C# barkod işlemlerinde null kontrolü, istisnaları önlemek ve barkod verilerinin eksik veya geçersiz olabileceği durumları hatasız bir şekilde ele alabilmek için önemlidir.

IronBarcode null kontrolüne nasıl yardımcı olabilir?

IronBarcode, null kontrolleri kolayca ele alacak yerleşik yöntemler sağlar, bu sayede geliştiriciler karmaşık doğrulama mantığını manuel olarak uygulamak zorunda kalmadan barkod verilerini güvenli bir şekilde yönetebilir.

IronBarcode'da null kontrolü için bazı en iyi uygulamalar nelerdir?

En iyi uygulamalar arasında null değerler için BarkodSonuçlarını kontrol etmek, işleme öncesi girdileri doğrulamak ve güven filtrelerini kullanarak güvenilir barkod tarama sonuçları sağlamak bulunur.

IronBarcode, null çıktılardan kaçınmak için sonuçları güvenle filtreleyebilir mi?

Evet, IronBarcode, barkod sonuçlarını güven seviyelerine göre filtreleme olanağı sunar, bu da null çıktıları azaltmaya yardımcı olur ve barkod okuma işlemlerinde yüksek doğruluk sağlar.

IronBarcode ile yazma girdilerini doğrulamanın bir yolu var mı?

IronBarcode, barkodlara kodlanan verilerin doğru ve eksiksiz olmasını sağlamak için yazma girdilerini doğrulama olanağı sunar ve barkod oluşturma sırasında sorunları önler.

Bir null barkod sonucu ele alınmazsa ne olur?

Bir null barkod sonucu ele alınmazsa, çalışma zamanı istisnalarına ve uygulama akışının kesilmesine neden olabilir, potansiyel çöküşlere veya hatalı işlemlere yol açabilir.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 2,169,908 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package BarCode
bir örnek çalıştırın dize barkod haline geldiğini görün.