C#'taki Barkod İşlemleri İçin Null Kontrolü Nasıl Yapılır

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

IronBarcode, tarama sonuçlarını BarcodeResults aracılığıyla C#'da bir BarcodeReader.Read koleksiyonu olarak döndürür. Bu yöntem, giriş görüntüsü tanınmazsa null döndürür veya barkodlar tespit edilmezse boş bir koleksiyon döndürür. BarcodeWriter.CreateBarcode, girdi null, boş veya geçersiz bir formatta ise bir istisna atar.

Kamera beslemeleri, belge yüklemeleri ve depo tarayıcıları gibi gerçek dünya tarama kaynakları her zaman okunabilir bir barkod sağlamayabilir. Null veya boş değerleri kontrol etmeden sonuç özelliklerine erişmek veya koleksiyonu yinelemek, çalışma zamanında NullReferenceException hatasına neden olabilir. Yazma API'sine geçersiz dizeler aktarmak, ArgumentException hatasına neden olabilir. Okuma ve yazma işlemlerinde önleyici önlemler almak, bu istisnaların üretimde önlenmesine yardımcı olur.

Bu nasıl yapılır klavuzu, IronBarcode okuma ve yazma işlemlerinde null ve boş sonuçlarla başa çıkmayı, koruyucu ifade, güven filtrelemesi ve yeniden kullanılabilir bir doğrulayıcı deseni kullanarak açıklar.


Hızlı Başlangıç: Barkod İşlemlerinde Null Sonuçları Ele Alma

Herhangi bir sonuç özelliğine erişmeden önce BarcodeResults koleksiyonunu güvenli bir şekilde kontrol etmek için IronBarcode'un koruma desenini kullanın. Hızlı bir şekilde başlamak için bu minimal okuma ve kontrol ile hemen başlayın:

  1. IronBarcode aşağıdaki NuGet Paket Yöneticisi ile yükleyin

    PM > Install-Package BarCode
  2. Bu kod parçacığını kopyalayın ve ç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 için dağıtım yapın

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

    arrow pointer

Null ve Boş Barkod Sonuçları Nasıl Ele Alınır?

İki hata modu vardır: BarcodeResults, girdi geçerli bir resim değilse null, resim BARCODE içermiyorsa boştur. First, Value'ye erişmek veya her iki koşulu da doğrulamadan yineleme yapmak, çalışma zamanı istisnasına neden olur.

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

Giriş

Bir Code128 BarCode'lu nakliye etiketi (başarılı yol) ve BarCode içermeyen boş bir resim (başarısız yol).

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, Value ve Text dize özelliklerini sağlar; her ikisi de kod çözülmüş BARCODE içeriğini döndürür. Ciddi şekilde hasar görmüş barkodlar veya kısmi taramalar boş veya boşluk değerleri üretebilir. Boş değerlerin alt sistemlere ulaşmasını önlemek için her sonuçta string.IsNullOrWhiteSpace kullanın.

BarcodeReaderOptions ayrıca, düşük kaliteli okumaları sonuç koleksiyonuna ulaşmadan önce eleyen bir ConfidenceThreshold özelliğine (0,0 ila 1,0) 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

Barkod Yazma İşlemlerine Null-Güvenli Desenler Nasıl Uygulanır?

BarcodeWriter.CreateBarcode bir dize değeri ve bir BarcodeWriterEncoding veya BarcodeEncoding enum alır. Null veya boş bir dize geçirmek hemen bir hata fırlatır. Biçim kısıtlamaları da geçerlidir: EAN-8 7 ila 8 basamaklı sayıları kabul eder, UPC-A 11 ila 12 basamaklı sayıları kabul eder ve Code 128 karakter sınırına sahiptir. Çağrıdan önce girdiyi doğrulamak, bu hataların kodlama adımında oluşması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 basamaklı giriş (1234567) taranabilir bir EAN-8 BarCode üretir. Null, boş veya sayısal olmayan girdiler koruyucu deyimler tarafından yakalanır ve hiçbir zaman kodlama adımına ulaşmaz.

Geçerli 7 haneli 1234567 girdisinden üretilen EAN-8 barkod

Yazma API'si de kendi dahili doğrulamalarını yapar: kontrol toplamlarını kontrol eder, uzunluk kısıtlamalarını onaylar ve seçilen kodlama için geçersiz karakterleri reddeder. Yukarıdaki koruma deyimleri, sorunları daha erken yakalar ve çağrıcıya hata mesajı üzerinde kontrol ve toparlanma yolu sağlar. Desteklenen kodlamaların ve kısıtlamalarının tam listesi için barkod oluşturma nasıl yapılır kılavuzu ve veriden barkod oluşturma rehberine bakın.


Aşağı Akış İşlemeden Önce Sonuçlar Nasıl Doğrulanır?

Barkod verileri başka bir sisteme (bir veritabanı yazması, bir API çağrısı, bir etiket yazıcı) aktarıldığında, sonuç sayısını, değer bütünlüğünü ve tür kontrollerini tek bir yeniden kullanılabilir metoda konsolide etmek yardımcı olur:

Giriş

Doğrulayıcı için okuma hedefi olarak kullanılan bir Code128 BarCode depo taraması.

Depo taraması için doğrulayıcı örneği olarak kullanılan Code128 barkod kodlaması WH-SCAN-4471
: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

Metod, null döndermek yerine boş bir liste döndürür, bu yüzden çağıranlar dönen değeri null kontrol etmek zorunda kalmazlar. İsteğe bağlı expectedType parametresi, sembolojiye göre filtreleme yapar; bu, bir tarama işlemi sırasında aynı görüntüden hem bir QR kodu hem de bir Code 128 algılandığında, alt sistemin beklenmedik formatlar almasını önler.

Birden çok dosyada toplu okuma için her dosya başına aynı deseni uygular ve sonuçları toplar. ExpectBarcodeTypes seçeneği, BarcodeReaderOptions üzerinde taramayı önceden beklenen sembolojilerle sınırlandırır, böylece doğrulayıcıya daha az istenmeyen sonuç ulaşır.


Daha Fazla Okuma

Lisans seçeneklerini görüntüleyin hattı üretim için 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 pürüzsüz barkod işleme sağlamak için bir barkod sonucu veya girişinin null olup olmadığını doğrulama işlemini içerir.

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

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

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

IronBarcode, geliştiricilerin karmaşık doğrulama mantığını manuel olarak uygulamadan barkod verilerini güvenli bir şekilde yönetmesine olanak tanıyan yerleşik yöntemler sağlar.

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

En iyi uygulamalar, null değerler için BarcodeResults'ü kontrol etmeyi, işlemden önce girdileri doğrulamayı ve güven filtrelerini kullanarak güvenilir barkod tarama sonuçları sağlamayı içerir.

IronBarcode güvene göre sonuçları filtreleyebilir mi?

Evet, IronBarcode güven seviyelerine göre barkod sonuçlarını filtrelemenize olanak tanır, bu da null çıktıları azaltmaya ve barkod okuma doğruluğunu artırmaya yardımcı olur.

IronBarcode ile yazma girdilerini doğrulamak mümkün mü?

IronBarcode, barkodlara kodlanan verinin doğru ve eksiksiz olduğunu doğrulamak için yazma girdilerinin doğrulanmasını sağlar ve bu da barkod oluşturma sırasında sorunların önlenmesine yardımcı olur.

Bir null barkod sonucu ele alınmazsa ne olur?

Eğer bir null barkod sonucu ele alınmazsa, çalışma zamanı istisnalarına yol açabilir ve uygulamanın akışını kesintiye uğratarak olası çöküşlere veya yanlış işlemlere neden olabilir.

IronBarcode, iş süreçlerindeki verimliliği artırmaya nasıl yardımcı olabilir?

IronBarcode, hızlı ve doğru barkod üretimi ve okuma yeteneği sağlayarak, manuel veri girişi hatalarını azaltır ve envanter ile varlık takibini iyileştirerek iş süreçlerinin verimliliğini artırır.

Bir projede IronBarcode'u uygulamak için hangi programlama becerileri gereklidir?

IronBarcode'u bir projede uygulamak için temel C# programlama bilgisi yeterlidir, çünkü bu kütüphane, geliştiricilere rehberlik eden basit yöntemler ve kapsamlı belgeler sağlar.

IronBarcode, hem küçük projeler hem de büyük kurumsal uygulamalar için uygun mu?

IronBarcode, küçük projeler kadar geniş çaplı kurumsal uygulamalar için de uygun, ölçeklenebilir ve çok yönlü olacak şekilde tasarlanmıştır ve sağlam barkod çözümleri gerektiren uygulamalara hizmet eder.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapı...

Daha Fazla Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 2,240,258 | Sürüm: 2026.5 just released
Still Scrolling Icon

Hâlâ Kaydırıyor Musunuz?

Hızlıca kanıt ister misiniz? PM > Install-Package BarCode
bir örnek çalıştır dizginizin barkoda dönüştüğünü izle.