# C#'taki Barkod İşlemleri İçin Null Kontrolü Nasıl Yapılır
IronBarcode, C# üzerinden `BarcodeReader.Read` ile tarama sonuçlarını bir `BarcodeResults` 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`, giriş null, boş veya geçersiz formatta olduğunda 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 koleksiyonu kontrol etmeden yineleme yapmak, çalışma zamanında bir `NullReferenceException` neden olabilir. Yazma API'sine geçersiz stringler iletmek bir `ArgumentException` ile sonuçlanabilir. 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.
<hr />
*as-heading:2(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 deseni kullanın. Hızlı bir şekilde başlamak için bu minimal okuma ve kontrol ile hemen başlayın:
```cs
:title=Guard BarcodeResults for Null and Empty
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);
```
<div class="hsg-featured-snippet">
<h2>IronBarcode ile Barkod İşlemleri İçin Null Kontrolü Nasıl Ele Alınır</h2>
<ol>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/BarCode/">IronBarcode kütüphanesini NuGet'ten indirin</a></li>
<li><code>BarcodeReader.Read</code> çağrın ve <code>BarcodeResults</code> döndürülen değeri yakalayın</li>
<li>Herhangi bir sonuca erişmeden önce null olup olmadığını kontrol edin</li>
<li>Aşağı akışı kullanmadan önce bireysel <code>BarcodeResult</code> özelliklerini doğrulayın</li>
<li>Düşük kaliteli okumaları tarama seviyesinde filtrelemek için <code>BarcodeReaderOptions</code> üzerinde <code>ConfidenceThreshold</code> ayarlayın</li>
</ol>
</div>
## Null ve Boş Barkod Sonuçları Nasıl Ele Alınır?
İki hata modu vardır: Giriş geçerli bir görüntü değilse `BarcodeResults` null döner ve görüntüde barkod yoksa boş döner. `First`, `Value` erişmek veya her iki koşulu doğrulamadan yineleme yapmak bir çalışma zamanı istisnasına neden olur.
İşleme döngüsüne girmeden önce her iki durumu da kontrol edin:
### Giriş
Bir `Code128` barkod sevkiyat etiketi (başarı yolu) ve barkodsuz boş bir görüntü (hata yolu).
<div style="display: flex; gap: 1rem; justify-content: center; flex-wrap: wrap;">
<div class="content-img-align-center" style="width: 45%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-shipping-label.png"
alt="Nakliye etiketi girişi olarak kullanılan SHP-20240001 kodlayan Code128 barkodu"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">shipping-label.png (başarı yolu)</p>
</div>
</div>
<div class="content-img-align-center" style="width: 45%;">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-blank-image.png"
alt="Boş sonuç yolunu tetiklemek için kullanılan, barkod içermeyen boş beyaz görüntü"
class="img-responsive add-shadow" />
<p style="color: #181818; font-style: italic; text-align: center;">blank-image.png (başarısızlık yolu, barkod yok)</p>
</div>
</div>
</div>
```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}");
}
```
Her `BarcodeResult`, her ikisi de kodlanmış barkod içeriğini döndüren `Value` ve `Text` string özelliklerini sağlar. 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ın sonuç koleksiyonuna ulaşmadan önce düşürüldüğü bir `ConfidenceThreshold` özelliğine (0,0 ila 1,0) sahiptir:
```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}");
```
---
## Barkod Yazma İşlemlerine Null-Güvenli Desenler Nasıl Uygulanır?
`BarcodeWriter.CreateBarcode` bir string değeri ve bir `BarcodeWriterEncoding` veya `BarcodeEncoding` enum alır. Null veya boş bir dize geçirmek hemen bir hata fırlatır. Format kısıtlamaları da geçerlidir: `EAN-8` 7 ila 8 rakam kabul eder, `UPC-A` 11 ila 12 rakam kabul eder ve `Code 128` bir karakter sınırına sahiptir. Çağrıdan önce girdiyi doğrulamak, bu hataların kodlama adımında oluşmasını engeller:
```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");
```
### Çıktı
Geçerli bir 7 haneli giriş (`1234567`), taranabilir bir `EAN-8` barkodu üretir. Null, boş veya sayısal olmayan girdiler koruyucu deyimler tarafından yakalanır ve hiçbir zaman kodlama adımına ulaşmaz.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/output-null-safe-write-barcode.png" alt="Geçerli 7 haneli 1234567 girdisinden üretilen EAN-8 barkod" class="img-responsive add-shadow" />
</div>
</div>
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](https://ironsoftware.com/csharp/barcode/examples/csharp-create-barcode/) ve [veriden barkod oluşturma rehberi](https://ironsoftware.com/csharp/barcode/how-to/create-barcode-from-data/)ne 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ş
Bir `Code128` barkod depo taraması, doğrulayıcı için okuma hedefi olarak kullanılır.
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/barcode/how-to/null-checking/input-warehouse-scan.png" alt="Depo taraması için doğrulayıcı örneği olarak kullanılan Code128 barkod kodlaması WH-SCAN-4471" class="img-responsive add-shadow" />
</div>
</div>
```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
}
```
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, bir tarama hem bir QR kodu hem de aynı resimden bir `Code 128` aldığında, alt sistemin beklenmeyen formatlar almasını önler.
Birden çok dosyada [toplu okuma](https://ironsoftware.com/csharp/barcode/tutorials/reading-barcodes/) için her dosya başına aynı deseni uygular ve sonuçları toplar. `ExpectBarcodeTypes` seçeneği, `BarcodeReaderOptions` üzerinde taramayı beklenen sembolojilere baştan daraltır, bu yüzden daha az istenmeyen sonuç doğrulayıcıya ulaşır.
---
## Daha Fazla Okuma
- [Barkodları Okuma Eğitimi](https://ironsoftware.com/csharp/barcode/tutorials/reading-barcodes/): tarama yapılandırması ve okuma seçenekleri.
- [Çıktı Veri Formatları Kılavuzu](https://ironsoftware.com/csharp/barcode/how-to/output-data-formats/): Tüm `BarcodeResult` özellikleri ve türleri.
- [Veriden Barkod Oluştur](https://ironsoftware.com/csharp/barcode/how-to/create-barcode-from-data/): her simge bilimi için kodlama kısıtlamaları.
- [BarcodeReaderOptions API Referansı](https://ironsoftware.com/csharp/barcode/object-reference/api/IronBarCode.BarcodeReaderOptions.html): tam yapılandırma belgeleri.
- [IronBarcode Değişiklik Günlüğü](https://ironsoftware.com/csharp/barcode/product-updates/changelog/): sürüme özel düzeltmeler ve özellik eklemeleri.
[Lisans seçeneklerini görüntüleyin](https://ironsoftware.com/csharp/barcode/licensing/) hattı üretim için hazır olduğunda.
IronBarcode, C# üzerinden BarcodeReader.Read ile tarama sonuçlarını bir BarcodeResults 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, giriş null, boş veya geçersiz formatta olduğunda 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 koleksiyonu kontrol etmeden yineleme yapmak, çalışma zamanında bir NullReferenceException neden olabilir. Yazma API'sine geçersiz stringler iletmek bir ArgumentException ile sonuçlanabilir. 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 deseni kullanın. Hızlı bir şekilde başlamak için bu minimal okuma ve kontrol ile hemen başlayın:
1Install IronBarcode with NuGet Package Manager
PM > Install-Package BarCode
Install-Package BarCode
2Bu kod parçacığını kopyalayın ve çalıştırın.
using IronBarCode;BarcodeResults results = BarcodeReader.Read("label.png");// Guard: null or emptyif (results is null || results.Count == 0){Console.WriteLine("No barcodes detected."); return;}Console.WriteLine(results.First().Value);
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#
3Canlı ortamınızda test için dağıtım yapın
Ücretsiz deneme ile bugün projenizde IronBarcode kullanmaya başlayın
IronBarcode ile Barkod İşlemleri İçin Null Kontrolü Nasıl Ele Alınır
BarcodeReader.Read çağrın ve BarcodeResults döndürülen değeri yakalayın
Herhangi bir sonuca erişmeden önce null olup olmadığını kontrol edin
Aşağı akışı kullanmadan önce bireysel BarcodeResult özelliklerini doğrulayın
Düşük kaliteli okumaları tarama seviyesinde filtrelemek için BarcodeReaderOptions üzerinde ConfidenceThreshold ayarlayın
Null ve Boş Barkod Sonuçları Nasıl Ele Alınır?
İki hata modu vardır: Giriş geçerli bir görüntü değilse BarcodeResults null döner ve görüntüde barkod yoksa boş döner. First, Value erişmek veya her iki koşulu doğrulamadan yineleme yapmak bir çalışma zamanı istisnasına neden olur.
İşleme döngüsüne girmeden önce her iki durumu da kontrol edin:
Giriş
Bir Code128 barkod sevkiyat etiketi (başarı yolu) ve barkodsuz boş bir görüntü (hata yolu).
shipping-label.png (başarı yolu)
blank-image.png (başarısızlık yolu, barkod yok)
using IronBarCode;// BarcodeReader.Read() returns a BarcodeResults collection, not a single resultBarcodeResults 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 barcodesif (results is null || results.Count == 0){ // Log, return a default, or throw a domain-specific exceptionConsole.WriteLine("No barcodes found in the input image."); return;}// Collection is safe to iterate; each BarcodeResult holds one decoded barcodeforeach (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}");}
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}");
}
ImportsIronBarCode' BarcodeReader.Read() returns a BarcodeResults collection, not a single resultDim results AsBarcodeResults = 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 barcodesIf results Is NothingOrElse results.Count = 0 Then ' Log, return a default, or throw a domain-specific exceptionConsole.WriteLine("No barcodes found in the input image.") ReturnEnd If' Collection is safe to iterate; each BarcodeResult holds one decoded barcodeFor Each result AsBarcodeResultIn results ' Guard individual result properties; partial scans or severely ' damaged barcodes can produce results where .Value is empty or whitespace IfString.IsNullOrWhiteSpace(result.Value) ThenConsole.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
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
Her BarcodeResult, her ikisi de kodlanmış barkod içeriğini döndüren Value ve Text string özelliklerini sağlar. 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ın sonuç koleksiyonuna ulaşmadan önce düşürüldüğü bir ConfidenceThreshold özelliğine (0,0 ila 1,0) sahiptir:
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 nullif (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}");
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}");
ImportsIronBarCode' 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 BarcodeReaderOptionsWith { .ConfidenceThreshold = 0.7 ' range 0.0 to 1.0; lower values accept weaker signals}Dim results AsBarcodeResults = 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 nullIf results Is NothingOrElse results.Count = 0 ThenConsole.WriteLine("No barcodes met the confidence threshold.") ReturnEnd IfFor Each result In resultsConsole.WriteLine($"Type: {result.BarcodeType}, Value: {result.Value}")Next
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
Barkod Yazma İşlemlerine Null-Güvenli Desenler Nasıl Uygulanır?
BarcodeWriter.CreateBarcode bir string değeri ve bir BarcodeWriterEncoding veya BarcodeEncoding enum alır. Null veya boş bir dize geçirmek hemen bir hata fırlatır. Format kısıtlamaları da geçerlidir: EAN-8 7 ila 8 rakam kabul eder, UPC-A 11 ila 12 rakam kabul eder ve Code 128 bir karakter sınırına sahiptir. Çağrıdan önce girdiyi doğrulamak, bu hataların kodlama adımında oluşmasını engeller:
using IronBarCode;// Input may arrive from user input, a database, or an API responsestring inputValue = GetValueFromUserOrDatabase(); // Could be null// Guard: null, empty, or whitespace input cannot produce a valid barcodeif (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 mismatchGeneratedBarcode barcode = BarcodeWriter.CreateBarcode(inputValue, encoding);barcode.SaveAsPng("output-barcode.png");
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");
ImportsIronBarCode' Input may arrive from user input, a database, or an API responseDim inputValue AsString = GetValueFromUserOrDatabase() ' Could be Nothing' Guard: null, empty, or whitespace input cannot produce a valid barcodeIfString.IsNullOrWhiteSpace(inputValue) ThenConsole.WriteLine("Cannot generate barcode: input value is null or empty.") ReturnEnd 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 AsBarcodeWriterEncoding = BarcodeWriterEncoding.EAN8If encoding = BarcodeWriterEncoding.EAN8AndAlsoNotSystem.Text.RegularExpressions.Regex.IsMatch(inputValue, "^\d{7,8}$") ThenConsole.WriteLine("EAN-8 requires exactly 7 or 8 numeric digits.") ReturnEnd If' Input is validated; CreateBarcode will not throw for null or format mismatchDim barcode AsGeneratedBarcode = 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")
Çıktı
Geçerli bir 7 haneli giriş (1234567), taranabilir bir EAN-8 barkodu üretir. Null, boş veya sayısal olmayan girdiler koruyucu deyimler tarafından yakalanır ve hiçbir zaman kodlama adımına ulaşmaz.
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ş
Bir Code128 barkod depo taraması, doğrulayıcı için okuma hedefi olarak kullanılır.
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 expectvar 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 checksforeach (var barcode in validated){SendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()); // placeholder for your downstream call}
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
}
ImportsIronBarCodeImportsSystem.Collections.GenericImportsSystem.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.PublicModuleBarcodeValidator Public Function GetValidResults( imagePath AsString,Optional expectedType AsBarcodeEncoding? = Nothing,Optional confidenceThreshold AsDouble = 0.7) AsList(OfBarcodeResult) ' Apply confidence threshold at scan level via BarcodeReaderOptions Dim options As New BarcodeReaderOptionsWith { .ConfidenceThreshold = confidenceThreshold } Dim results AsBarcodeResults = BarcodeReader.Read(imagePath, options) ' Return empty list instead of null so callers never need to null-check the return value If results Is NothingOrElse results.Count = 0 Then Return New List(OfBarcodeResult)() End If Return results _ .Where(Function(r) NotString.IsNullOrWhiteSpace(r.Value)) _ ' skip results with empty decoded data .Where(Function(r) expectedType Is NothingOrElse r.BarcodeType = expectedType) _ ' null accepts any symbology .ToList() End FunctionEndModule' Usage: pass the image path and the symbology you expectDim 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 ReturnEnd If' All results have passed null, empty, type, and confidence checksFor Each barcode In validatedSendToInventorySystem(barcode.Value, barcode.BarcodeType.ToString()) ' placeholder for your downstream callNext barcode
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
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, bir tarama hem bir QR kodu hem de aynı resimden bir Code 128 aldığında, alt sistemin beklenmeyen 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ı beklenen sembolojilere baştan daraltır, bu yüzden daha az istenmeyen sonuç doğrulayıcıya ulaşır.
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.
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, 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ılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.