Cómo manejar errores y depurar operaciones de códigos de barras en C#
Los procesos de procesamiento de códigos de barras pueden fallar de forma silenciosa, y la ausencia de resultados a menudo se confunde con «no hay BarCode presente». Sin embargo, problemas como archivos dañados, archivos PDF protegidos con contraseña o incompatibilidades de formato pueden ser los responsables. La implementación de un registro adecuado y una gestión estructurada de los errores permite detectar estos fallos y proporciona diagnósticos útiles.
IronBarcode ofrece una jerarquía de excepciones tipadas en el espacio de nombres IronBarCode.Exceptions, una API de registro integrada y propiedades detalladas de BarcodeResult. Estas propiedades incluyen el formato detectado, el valor descodificado, el número de página y las coordenadas de cada descodificación correcta.
Este tutorial explica cómo capturar e interpretar excepciones tipadas, extraer el contexto de diagnóstico de lecturas fallidas, habilitar registros estructurados y aislar fallos durante operaciones en lote.
Inicio rápido: Manejar errores de código de barras y habilitar diagnósticosEncapsule las llamadas de lectura/escritura en bloques try-catch dirigidos a las excepciones tipificadas de IronBarcode para mostrar mensajes de error que permitan tomar medidas en lugar de fallos silenciosos.
-
1Instalar IronBarcode con NuGet Package Manager
-
2Copie y ejecute este fragmento de código.
using IronBarCode; using IronBarCode.Exceptions; try { BarcodeResults results = BarcodeReader.Read("label.pdf"); Console.WriteLine($"Found {results.Count} barcode(s)"); } catch (IronBarCodeFileException ex) { Console.Error.WriteLine($"File error: {ex.Message}"); }Imports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End TryImports IronBarCode Imports IronBarCode.Exceptions Try Dim results As BarcodeResults = BarcodeReader.Read("label.pdf") Console.WriteLine($"Found {results.Count} barcode(s)") Catch ex As IronBarCodeFileException Console.Error.WriteLine($"File error: {ex.Message}") End Try -
3Despliegue para probar en su entorno real
Empiece a usar IronBarcode en su proyecto hoy con una prueba gratuita
Cómo gestionar los errores de BarCode y habilitar el diagnóstico con IronBarcode
- Descargue la biblioteca IronBarcode desde NuGet
- Encapsule las llamadas de lectura/escritura en bloques try-catch dirigidos a tipos de excepciones específicas
- Inspeccione
BarcodeResultspara entradas vacías o de baja confianza después de una lectura exitosa - Habilite
IronSoftware.Loggerpara capturar la salida de diagnóstico interno - Aísle fallos por archivo en operaciones por lotes con lógica de continuar ante errores
¿Cómo puedo detectar e interpretar las excepciones de IronBarcode?
Capture las excepciones de IronBarcode, desde las más específicas hasta las más generales. Ordene los bloques catch para gestionar primero las excepciones procesables, como los errores de archivo, de contraseña de PDF y de codificación, seguidos del tipo base. El espacio de nombres IronBarCode.Exceptions define 11 tipos de excepciones, cada uno correspondiente a un modo de falla específico:
| Tipo de excepción | Desencadenante | Solución recomendada |
|---|---|---|
IronBarCodeFileException | El archivo está dañado, bloqueado o tiene un formato de imagen no compatible | Compruebe que el archivo tenga un formato de imagen compatible y que no esté bloqueado; además, capture por separado las excepciones FileNotFoundException para los archivos que falten. |
IronBarCodePdfPasswordException | PDF protegido por contraseña o encriptado | Suministre la contraseña a través de PdfBarcodeReaderOptions, o salte el archivo y registre |
IronBarCodeEncodingException | Fallo genérico de codificación durante la generación de código de barras | Verifique que los datos de entrada coincidan con las restricciones de BarcodeWriterEncoding objetivo |
IronBarCodeContentTooLongEncodingException | El valor excede el límite de caracteres para la simbología seleccionada | Trunque los datos o cambie a un formato de mayor capacidad (QR, DataMatrix) |
IronBarCodeFormatOnlyAcceptsNumericValuesEncodingException | Caracteres no numéricos pasados a un formato de solo numérico (EAN, UPC) | Limpie la entrada o cambie a un formato alfanumérico (Code128, Code39) |
IronBarCodeUnsupportedRendererEncodingException | La codificación seleccionada BarcodeEncoding no se puede generar con IronBarcode | Use la enumeración BarcodeWriterEncoding en lugar de BarcodeEncoding |
IronBarCodeParsingException | Los datos estructurados (GS1-128) fallan en la validación durante el análisis | Valide la estructura GS1 con Code128GS1Parser.IsValid() antes de analizar |
IronBarCodeNativeException | Error en la capa de interoperabilidad nativa (DLLs faltantes, incompatibilidad de plataforma) | Verifique que los paquetes específicos de la plataforma NuGet estén instalados (BarCode.Linux, BarCode.macOS) |
IronBarCodeConfidenceThresholdException | Argumento de umbral de confianza inválido pasado a opciones de lector | Asegúrese de que ConfidenceThreshold esté entre 0.0 y 1.0 |
IronBarCodeUnsupportedException | Operación no soportada en el contexto actual | Consulte el registro de cambios para verificar la disponibilidad de características en su versión |
IronBarCodeException | Tipo base - captura cualquier error específico de IronBarcode que no coincida con los anteriores | Registre los detalles completos de la excepción y escale para la investigación |
Use filtros de excepciones con cláusulas when para direccionar tipos de excepciones superpuestas sin anidamiento profundo. Los archivos faltantes lanzan la excepción estándar System.IO.FileNotFoundException en lugar de IronBarCodeFileException, así que incluya un bloque catch separado para este caso:
Entrada
Un BarCode Code128 que codifica un número de factura (ruta de éxito) y un BarCode de etiqueta de almacén que representa el contenido del PDF que falta (ruta de error).

scanned-invoice.png (ruta de éxito)

warehouse-labels.pdf (ruta de falla: archivo no presente en el disco)
using IronBarCode;
using IronBarCode.Exceptions;
// Success path: valid file present on disk
string filePath = "scanned-invoice.png";
// Failure path: file does not exist → caught by FileNotFoundException below
// string filePath = "warehouse-labels.pdf";
try
{
BarcodeResults results = BarcodeReader.Read(filePath);
foreach (BarcodeResult result in results)
{
// Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}");
}
}
catch (IronBarCodePdfPasswordException ex)
{
// PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
// File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (FileNotFoundException ex)
{
// Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
// The when filter routes only missing-DLL errors here; other native exceptions
// fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
// Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}using IronBarCode;
using IronBarCode.Exceptions;
// Success path: valid file present on disk
string filePath = "scanned-invoice.png";
// Failure path: file does not exist → caught by FileNotFoundException below
// string filePath = "warehouse-labels.pdf";
try
{
BarcodeResults results = BarcodeReader.Read(filePath);
foreach (BarcodeResult result in results)
{
// Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}");
}
}
catch (IronBarCodePdfPasswordException ex)
{
// PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}");
}
catch (IronBarCodeFileException ex)
{
// File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}");
}
catch (FileNotFoundException ex)
{
// Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}");
}
catch (IronBarCodeNativeException ex) when (ex.Message.Contains("DLL"))
{
// The when filter routes only missing-DLL errors here; other native exceptions
// fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}");
}
catch (IronBarCodeException ex)
{
// Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}");
}Imports IronBarCode
Imports IronBarCode.Exceptions
' Success path: valid file present on disk
Dim filePath As String = "scanned-invoice.png"
' Failure path: file does not exist → caught by FileNotFoundException below
' Dim filePath As String = "warehouse-labels.pdf"
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath)
For Each result As BarcodeResult In results
' Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}")
Next
Catch ex As IronBarCodePdfPasswordException
' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
' File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As FileNotFoundException
' Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
' The when filter routes only missing-DLL errors here; other native exceptions
' fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
' Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End TryImports IronBarCode
Imports IronBarCode.Exceptions
' Success path: valid file present on disk
Dim filePath As String = "scanned-invoice.png"
' Failure path: file does not exist → caught by FileNotFoundException below
' Dim filePath As String = "warehouse-labels.pdf"
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath)
For Each result As BarcodeResult In results
' Print the detected symbology and decoded value for each barcode found
Console.WriteLine($"[{result.BarcodeType}] {result.Value}")
Next
Catch ex As IronBarCodePdfPasswordException
' PDF is encrypted — supply the password via PdfBarcodeReaderOptions before retrying
Console.Error.WriteLine($"PDF requires password: {filePath} — {ex.Message}")
Catch ex As IronBarCodeFileException
' File is present but corrupted, locked, or in an unsupported format
Console.Error.WriteLine($"Cannot read file: {filePath} — {ex.Message}")
Catch ex As FileNotFoundException
' Missing files throw FileNotFoundException, not IronBarCodeFileException
Console.Error.WriteLine($"File not found: {filePath} — {ex.Message}")
Catch ex As IronBarCodeNativeException When ex.Message.Contains("DLL")
' The when filter routes only missing-DLL errors here; other native exceptions
' fall through to the IronBarCodeException block below
Console.Error.WriteLine($"Missing native dependency: {ex.Message}")
Catch ex As IronBarCodeException
' Base catch for any IronBarcode-specific error not matched by the blocks above
Console.Error.WriteLine($"IronBarcode error: {ex.GetType().Name} — {ex.Message}")
End TryResultado
![Salida de la consola que muestra la decodificación correcta de Code128: [Code128] INV-2024-7829](/static-assets/barcode/how-to/detailed-error-messages/output-exception-hierarchy-success.webp)
Un archivo faltante activa FileNotFoundException, dirigida por el bloque catch dedicado.

El filtro when (ex.Message.Contains("DLL")) en IronBarCodeNativeException dirige los errores de dependencia faltante a un manejador específico sin afectar otras excepciones nativas. Este enfoque resulta especialmente útil en implementaciones de Docker, donde pueden faltar paquetes específicos de la plataforma.
IronSoftware.Exceptions.LicensingException se lanza por separado cuando la clave de licencia es inválida o falta. Capture esta excepción al inicio de la aplicación en lugar de en cada llamada de lectura o escritura individual.
¿Cómo extraigo los detalles de diagnóstico de las lecturas fallidas?
Una operación de lectura que devuelve cero resultados no es una excepción; produce una colección BarcodeResults vacía. El contexto de diagnóstico se obtiene inspeccionando los parámetros de entrada, las opciones configuradas y cualquier resultado parcial devuelto.
El objeto BarcodeResult proporciona propiedades útiles para el análisis post-mortem, incluyendo BarcodeType, Value, PageNumber, y Points (coordenadas de esquina). Si hay resultados presentes pero inesperados, primero verifique BarcodeType contra el formato esperado y verifique PageNumber.
Entrada
Un código de barras Code128 codificando un número de factura, leído con ExpectBarcodeTypes configurado en Code128 y QRCode, y ReadingSpeed.Detailed para un escaneo exhaustivo.

using IronBarCode;
string filePath = "scanned-invoice.png";
// Configure the reader to narrow the search to specific symbologies and use
// a thorough scan pass — narrows false positives and improves decode accuracy
var options = new BarcodeReaderOptions
{
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formats
Speed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged images
ExpectMultipleBarcodes = true // scan the full image rather than stopping at the first match
};
BarcodeResults results = BarcodeReader.Read(filePath, options);
// An empty result is not an exception — it means no barcode matched the configured options
if (results == null || results.Count == 0)
{
// Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}");
Console.Error.WriteLine($" Speed: {options.Speed}");
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
foreach (BarcodeResult result in results)
{
// Points contains the four corner coordinates of the barcode in the image;
// use the first corner as a representative position indicator
string pos = result.Points.Length > 0 ? $"{result.Points[0].X:F0},{result.Points[0].Y:F0}" : "N/A";
Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
+ $"(Page: {result.PageNumber}, Position: {pos})");
}
}using IronBarCode;
string filePath = "scanned-invoice.png";
// Configure the reader to narrow the search to specific symbologies and use
// a thorough scan pass — narrows false positives and improves decode accuracy
var options = new BarcodeReaderOptions
{
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit scan to known formats
Speed = ReadingSpeed.Detailed, // slower but more thorough — use ExtremeDetail for damaged images
ExpectMultipleBarcodes = true // scan the full image rather than stopping at the first match
};
BarcodeResults results = BarcodeReader.Read(filePath, options);
// An empty result is not an exception — it means no barcode matched the configured options
if (results == null || results.Count == 0)
{
// Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}");
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}");
Console.Error.WriteLine($" Speed: {options.Speed}");
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes");
}
else
{
foreach (BarcodeResult result in results)
{
// Points contains the four corner coordinates of the barcode in the image;
// use the first corner as a representative position indicator
string pos = result.Points.Length > 0 ? $"{result.Points[0].X:F0},{result.Points[0].Y:F0}" : "N/A";
Console.WriteLine($"[{result.BarcodeType}] {result.Value} "
+ $"(Page: {result.PageNumber}, Position: {pos})");
}
}Imports IronBarCode
Dim filePath As String = "scanned-invoice.png"
' Configure the reader to narrow the search to specific symbologies and use
' a thorough scan pass — narrows false positives and improves decode accuracy
Dim options As New BarcodeReaderOptions With {
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit scan to known formats
.Speed = ReadingSpeed.Detailed, ' slower but more thorough — use ExtremeDetail for damaged images
.ExpectMultipleBarcodes = True ' scan the full image rather than stopping at the first match
}
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
' An empty result is not an exception — it means no barcode matched the configured options
If results Is Nothing OrElse results.Count = 0 Then
' Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}")
Console.Error.WriteLine($" Speed: {options.Speed}")
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
For Each result As BarcodeResult In results
' Points contains the four corner coordinates of the barcode in the image;
' use the first corner as a representative position indicator
Dim pos As String = If(result.Points.Length > 0, $"{result.Points(0).X:F0},{result.Points(0).Y:F0}", "N/A")
Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
$"(Page: {result.PageNumber}, Position: {pos})")
Next
End IfImports IronBarCode
Dim filePath As String = "scanned-invoice.png"
' Configure the reader to narrow the search to specific symbologies and use
' a thorough scan pass — narrows false positives and improves decode accuracy
Dim options As New BarcodeReaderOptions With {
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit scan to known formats
.Speed = ReadingSpeed.Detailed, ' slower but more thorough — use ExtremeDetail for damaged images
.ExpectMultipleBarcodes = True ' scan the full image rather than stopping at the first match
}
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
' An empty result is not an exception — it means no barcode matched the configured options
If results Is Nothing OrElse results.Count = 0 Then
' Log the configured options alongside the warning so the cause is immediately actionable
Console.Error.WriteLine($"[WARN] No barcodes found in: {filePath}")
Console.Error.WriteLine($" ExpectedTypes: {options.ExpectBarcodeTypes}")
Console.Error.WriteLine($" Speed: {options.Speed}")
Console.Error.WriteLine($" Action: Retry with ReadingSpeed.ExtremeDetail or broaden ExpectBarcodeTypes")
Else
For Each result As BarcodeResult In results
' Points contains the four corner coordinates of the barcode in the image;
' use the first corner as a representative position indicator
Dim pos As String = If(result.Points.Length > 0, $"{result.Points(0).X:F0},{result.Points(0).Y:F0}", "N/A")
Console.WriteLine($"[{result.BarcodeType}] {result.Value} " &
$"(Page: {result.PageNumber}, Position: {pos})")
Next
End IfResultado
ExpectBarcodeTypes coincide con el código de barras en la imagen, la lectura devuelve el tipo, valor, número de página y posición.
Si ExpectBarcodeTypes no incluye la simbología real, la lectura devuelve un resultado vacío. El bloque [WARN] registra los tipos configurados, la velocidad de lectura y una sugerencia de acción a seguir.
![Salida de la consola que muestra [WARN] no se han encontrado BarCodes con ExpectBarcodeTypes establecido en Code39 para una imagen Code128](/static-assets/barcode/how-to/detailed-error-messages/output-diagnostic-logging-failure.webp)
Durante el diagnóstico surgen dos patrones comunes. Resultados vacíos con una configuración ExpectBarcodeTypes estrecha a menudo significan que el código de barras usa una simbología diferente; expandir a BarcodeEncoding.All puede confirmar esto. Los resultados de decodificación inesperados suelen indicar una mala calidad de la imagen.
Aplicar filtros de imagen y volver a intentarlo con una velocidad de lectura más lenta suele resolver estos problemas. También puede alternar la opción RemoveFalsePositive para eliminar lecturas fantasma de fondos ruidosos.
¿Cómo activo el registro detallado para las operaciones con BarCodes?
IronBarcode expone una API de registro integrada a través de IronSoftware.Logger. Configure el modo de registro y la ruta del archivo antes de realizar cualquier operación con BarCodes para capturar la salida de diagnóstico interna de los procesos de lectura y escritura.
Entrada
Una imagen TIFF de BarCode Code128 utilizada como objetivo de lectura mientras el registro detallado está activo.

using IronBarCode;
// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
// LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"; // path is relative to the working directory
// All subsequent operations will write internal processing steps to the log file:
// image pre-processing stages, format detection attempts, and native interop calls
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Detailed,
ExpectBarcodeTypes = BarcodeEncoding.All // scan for every supported symbology
};
BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");using IronBarCode;
// Enable IronBarcode's built-in logging — set BEFORE any read/write calls
// LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log"; // path is relative to the working directory
// All subsequent operations will write internal processing steps to the log file:
// image pre-processing stages, format detection attempts, and native interop calls
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Detailed,
ExpectBarcodeTypes = BarcodeEncoding.All // scan for every supported symbology
};
BarcodeResults results = BarcodeReader.Read("problem-scan.tiff", options);
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.");Imports IronBarCode
' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
' LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log" ' path is relative to the working directory
' All subsequent operations will write internal processing steps to the log file:
' image pre-processing stages, format detection attempts, and native interop calls
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Detailed,
.ExpectBarcodeTypes = BarcodeEncoding.All ' scan for every supported symbology
}
Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")Imports IronBarCode
' Enable IronBarcode's built-in logging — set BEFORE any read/write calls
' LoggingModes.All writes both debug output and file-level diagnostics
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "ironbarcode-debug.log" ' path is relative to the working directory
' All subsequent operations will write internal processing steps to the log file:
' image pre-processing stages, format detection attempts, and native interop calls
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Detailed,
.ExpectBarcodeTypes = BarcodeEncoding.All ' scan for every supported symbology
}
Dim results As BarcodeResults = BarcodeReader.Read("problem-scan.tiff", options)
Console.WriteLine($"Read complete. Results: {results.Count}. See ironbarcode-debug.log for details.")LoggingModes.All captura tanto la salida del depurador como el registro a nivel de archivo. El archivo de registro recoge los pasos de procesamiento internos, como las etapas de preprocesamiento de imágenes, los intentos de detección de formato y las llamadas de interoperabilidad nativas, que no son visibles a través de la API pública.
Para líneas de producción que usan un marco de registro estructurado (Serilog, NLog, Microsoft.Extensions.Logging), envolver operaciones de IronBarcode en una capa de middleware añade entradas JSON estructuradas junto al archivo de registro integrado. El registrador integrado escribe diagnósticos en texto plano útiles para escalamiento de soporte; El contenedor estructurado proporciona campos consultables para la pila de observabilidad.
using IronBarCode;
using System.Diagnostics;
// Lightweight wrapper that adds structured JSON observability to every read call.
// Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
var sw = Stopwatch.StartNew(); // start timing before the read so setup overhead is included
try
{
BarcodeResults results = BarcodeReader.Read(filePath, options);
sw.Stop();
// Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
+ $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
return results;
}
catch (Exception ex)
{
sw.Stop();
// Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
+ $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
+ $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
throw; // rethrow so the caller's catch blocks still handle the exception normally
}
}using IronBarCode;
using System.Diagnostics;
// Lightweight wrapper that adds structured JSON observability to every read call.
// Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
BarcodeResults ReadWithDiagnostics(string filePath, BarcodeReaderOptions options)
{
var sw = Stopwatch.StartNew(); // start timing before the read so setup overhead is included
try
{
BarcodeResults results = BarcodeReader.Read(filePath, options);
sw.Stop();
// Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"ok\","
+ $"\"count\":{results.Count},\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
return results;
}
catch (Exception ex)
{
sw.Stop();
// Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{\"file\":\"{filePath}\",\"status\":\"error\","
+ $"\"exception\":\"{ex.GetType().Name}\",\"message\":\"{ex.Message}\","
+ $"\"elapsed_ms\":{sw.ElapsedMilliseconds}}}");
throw; // rethrow so the caller's catch blocks still handle the exception normally
}
}Imports IronBarCode
Imports System.Diagnostics
' Lightweight wrapper that adds structured JSON observability to every read call.
' Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
Dim sw As Stopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is included
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
sw.Stop()
' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Return results
Catch ex As Exception
sw.Stop()
' Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Throw ' rethrow so the caller's catch blocks still handle the exception normally
End Try
End FunctionImports IronBarCode
Imports System.Diagnostics
' Lightweight wrapper that adds structured JSON observability to every read call.
' Call this in place of BarcodeReader.Read wherever elapsed-time and status logging is needed.
Function ReadWithDiagnostics(filePath As String, options As BarcodeReaderOptions) As BarcodeResults
Dim sw As Stopwatch = Stopwatch.StartNew() ' start timing before the read so setup overhead is included
Try
Dim results As BarcodeResults = BarcodeReader.Read(filePath, options)
sw.Stop()
' Emit a structured success entry to stdout — pipe to Fluentd, Datadog, or CloudWatch
Console.WriteLine($"{{""file"":""{filePath}"",""status"":""ok"",""count"":{results.Count},""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Return results
Catch ex As Exception
sw.Stop()
' Emit a structured error entry to stderr with exception type, message, and elapsed time
Console.Error.WriteLine($"{{""file"":""{filePath}"",""status"":""error"",""exception"":""{ex.GetType().Name}"",""message"":""{ex.Message}"",""elapsed_ms"":{sw.ElapsedMilliseconds}}}")
Throw ' rethrow so the caller's catch blocks still handle the exception normally
End Try
End FunctionEl resultado estructurado se integra directamente con herramientas de agregación de registros. Redirija stdout a Fluentd, Datadog o CloudWatch en un despliegue en contenedores. El campo de tiempo transcurrido destaca las regresiones de rendimiento antes de que se conviertan en incumplimientos del SLA.
Resultado

¿Cómo depuro el procesamiento por lotes de BarCodes?
Procese varios archivos aislando cada lectura en su propio bloque try-catch, registrando los resultados de cada archivo y generando un resumen agregado. El proceso continúa a pesar de los fallos, en lugar de detenerse ante el primer error.
Entrada
Cuatro de las cinco imágenes de códigos de barras Code128 del directorio de lotes scans/. El quinto archivo (scan-05-broken.png) contiene bytes inválidos para activar una excepción de archivo.

Lote 1 - Escaneo 1

Lote 1 - Escaneo 2

Lote 1 - Escaneo 3

Lote 1 - Escaneo 4
using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;
// Enable built-in logging for the entire batch run so internal processing steps
// are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";
// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced, // balances throughput vs accuracy
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formats
ExpectMultipleBarcodes = true // scan each file fully
};
// Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>(); // per-file error context for root cause analysis
var sw = Stopwatch.StartNew();
foreach (string file in files)
{
try
{
BarcodeResults results = BarcodeReader.Read(file, options);
// Empty result is not an exception — the file was read but contained no matching barcode
if (results == null || results.Count == 0)
{
emptyCount++;
errors.Add((file, "No barcodes detected")); // record so caller can adjust options
continue;
}
foreach (BarcodeResult result in results)
{
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}");
}
successCount++;
}
catch (IronBarCodePdfPasswordException)
{
// PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount++;
errors.Add((file, "Password-protected PDF"));
}
catch (IronBarCodeFileException ex)
{
// File is corrupted, locked, or in an unsupported image format
failCount++;
errors.Add((file, $"File error: {ex.Message}"));
}
catch (FileNotFoundException ex)
{
// File was in the directory listing but deleted before the read completed (race condition)
failCount++;
errors.Add((file, $"File not found: {ex.Message}"));
}
catch (IronBarCodeException ex)
{
// Catch-all for any other IronBarcode-specific errors not handled above
failCount++;
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
}
catch (Exception ex)
{
// Unexpected non-IronBarcode error — log the full type for investigation
failCount++;
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
}
}
sw.Stop();
// Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files: {files.Length}");
Console.WriteLine($"Success: {successCount}");
Console.WriteLine($"Empty reads: {emptyCount}");
Console.WriteLine($"Failures: {failCount}");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s");
if (errors.Any())
{
Console.WriteLine("\n--- Error Details ---");
foreach (var (errorFile, errorMsg) in errors)
{
Console.Error.WriteLine($" {Path.GetFileName(errorFile)}: {errorMsg}");
}
}using IronBarCode;
using IronBarCode.Exceptions;
using System.Diagnostics;
// Enable built-in logging for the entire batch run so internal processing steps
// are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All;
IronSoftware.Logger.LogFilePath = "batch-run.log";
// Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
string[] files = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly);
var options = new BarcodeReaderOptions
{
Speed = ReadingSpeed.Balanced, // balances throughput vs accuracy
ExpectBarcodeTypes = BarcodeEncoding.Code128 | BarcodeEncoding.QRCode, // limit to known formats
ExpectMultipleBarcodes = true // scan each file fully
};
// Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
int successCount = 0;
int failCount = 0;
int emptyCount = 0;
var errors = new List<(string File, string Error)>(); // per-file error context for root cause analysis
var sw = Stopwatch.StartNew();
foreach (string file in files)
{
try
{
BarcodeResults results = BarcodeReader.Read(file, options);
// Empty result is not an exception — the file was read but contained no matching barcode
if (results == null || results.Count == 0)
{
emptyCount++;
errors.Add((file, "No barcodes detected")); // record so caller can adjust options
continue;
}
foreach (BarcodeResult result in results)
{
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}");
}
successCount++;
}
catch (IronBarCodePdfPasswordException)
{
// PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount++;
errors.Add((file, "Password-protected PDF"));
}
catch (IronBarCodeFileException ex)
{
// File is corrupted, locked, or in an unsupported image format
failCount++;
errors.Add((file, $"File error: {ex.Message}"));
}
catch (FileNotFoundException ex)
{
// File was in the directory listing but deleted before the read completed (race condition)
failCount++;
errors.Add((file, $"File not found: {ex.Message}"));
}
catch (IronBarCodeException ex)
{
// Catch-all for any other IronBarcode-specific errors not handled above
failCount++;
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"));
}
catch (Exception ex)
{
// Unexpected non-IronBarcode error — log the full type for investigation
failCount++;
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"));
}
}
sw.Stop();
// Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine("\n--- Batch Summary ---");
Console.WriteLine($"Total files: {files.Length}");
Console.WriteLine($"Success: {successCount}");
Console.WriteLine($"Empty reads: {emptyCount}");
Console.WriteLine($"Failures: {failCount}");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s");
if (errors.Any())
{
Console.WriteLine("\n--- Error Details ---");
foreach (var (errorFile, errorMsg) in errors)
{
Console.Error.WriteLine($" {Path.GetFileName(errorFile)}: {errorMsg}");
}
}Imports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
' Enable built-in logging for the entire batch run so internal processing steps
' are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"
' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit to known formats
.ExpectMultipleBarcodes = True ' scan each file fully
}
' Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))() ' per-file error context for root cause analysis
Dim sw As Stopwatch = Stopwatch.StartNew()
For Each file As String In files
Try
Dim results As BarcodeResults = BarcodeReader.Read(file, options)
' Empty result is not an exception — the file was read but contained no matching barcode
If results Is Nothing OrElse results.Count = 0 Then
emptyCount += 1
errors.Add((file, "No barcodes detected")) ' record so caller can adjust options
Continue For
End If
For Each result As BarcodeResult In results
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}")
Next
successCount += 1
Catch ex As IronBarCodePdfPasswordException
' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount += 1
errors.Add((file, "Password-protected PDF"))
Catch ex As IronBarCodeFileException
' File is corrupted, locked, or in an unsupported image format
failCount += 1
errors.Add((file, $"File error: {ex.Message}"))
Catch ex As FileNotFoundException
' File was in the directory listing but deleted before the read completed (race condition)
failCount += 1
errors.Add((file, $"File not found: {ex.Message}"))
Catch ex As IronBarCodeException
' Catch-all for any other IronBarcode-specific errors not handled above
failCount += 1
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
Catch ex As Exception
' Unexpected non-IronBarcode error — log the full type for investigation
failCount += 1
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
End Try
Next
sw.Stop()
' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files: {files.Length}")
Console.WriteLine($"Success: {successCount}")
Console.WriteLine($"Empty reads: {emptyCount}")
Console.WriteLine($"Failures: {failCount}")
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s")
If errors.Any() Then
Console.WriteLine(vbCrLf & "--- Error Details ---")
For Each errorDetail In errors
Console.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
Next
End IfImports IronBarCode
Imports IronBarCode.Exceptions
Imports System.Diagnostics
' Enable built-in logging for the entire batch run so internal processing steps
' are captured in the log file alongside the per-file console output
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.All
IronSoftware.Logger.LogFilePath = "batch-run.log"
' Collect all files in the directory — SearchOption.TopDirectoryOnly skips subdirectories
Dim files As String() = Directory.GetFiles("scans/", "*.*", SearchOption.TopDirectoryOnly)
Dim options As New BarcodeReaderOptions With {
.Speed = ReadingSpeed.Balanced, ' balances throughput vs accuracy
.ExpectBarcodeTypes = BarcodeEncoding.Code128 Or BarcodeEncoding.QRCode, ' limit to known formats
.ExpectMultipleBarcodes = True ' scan each file fully
}
' Three outcome counters: success (decoded), empty (read OK but no barcode found), fail (exception)
Dim successCount As Integer = 0
Dim failCount As Integer = 0
Dim emptyCount As Integer = 0
Dim errors As New List(Of (File As String, Error As String))() ' per-file error context for root cause analysis
Dim sw As Stopwatch = Stopwatch.StartNew()
For Each file As String In files
Try
Dim results As BarcodeResults = BarcodeReader.Read(file, options)
' Empty result is not an exception — the file was read but contained no matching barcode
If results Is Nothing OrElse results.Count = 0 Then
emptyCount += 1
errors.Add((file, "No barcodes detected")) ' record so caller can adjust options
Continue For
End If
For Each result As BarcodeResult In results
Console.WriteLine($"{Path.GetFileName(file)} | {result.BarcodeType} | {result.Value}")
Next
successCount += 1
Catch ex As IronBarCodePdfPasswordException
' PDF is password-protected — supply password via PdfBarcodeReaderOptions to recover
failCount += 1
errors.Add((file, "Password-protected PDF"))
Catch ex As IronBarCodeFileException
' File is corrupted, locked, or in an unsupported image format
failCount += 1
errors.Add((file, $"File error: {ex.Message}"))
Catch ex As FileNotFoundException
' File was in the directory listing but deleted before the read completed (race condition)
failCount += 1
errors.Add((file, $"File not found: {ex.Message}"))
Catch ex As IronBarCodeException
' Catch-all for any other IronBarcode-specific errors not handled above
failCount += 1
errors.Add((file, $"{ex.GetType().Name}: {ex.Message}"))
Catch ex As Exception
' Unexpected non-IronBarcode error — log the full type for investigation
failCount += 1
errors.Add((file, $"Unexpected: {ex.GetType().Name}: {ex.Message}"))
End Try
Next
sw.Stop()
' Summary report — parse failCount > 0 in CI/CD to set a non-zero exit code
Console.WriteLine(vbCrLf & "--- Batch Summary ---")
Console.WriteLine($"Total files: {files.Length}")
Console.WriteLine($"Success: {successCount}")
Console.WriteLine($"Empty reads: {emptyCount}")
Console.WriteLine($"Failures: {failCount}")
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalSeconds:F1}s")
If errors.Any() Then
Console.WriteLine(vbCrLf & "--- Error Details ---")
For Each errorDetail In errors
Console.Error.WriteLine($" {Path.GetFileName(errorDetail.File)}: {errorDetail.Error}")
Next
End IfResultado

Durante la ejecución, la consola muestra una línea por cada BarCode descodificado, seguida de un resumen con el recuento de archivos, los éxitos, las lecturas vacías, los fallos y el tiempo transcurrido. Los errores se enumeran con sus correspondientes nombres de archivo y los motivos del fallo.
El proceso distingue tres categorías de resultados: éxito (BarCodes encontrados y descodificados), vacío (archivo leído pero sin BarCodes detectados) y fallo (excepción lanzada). Esta distinción es importante porque las lecturas vacías y los errores requieren respuestas diferentes. Las lecturas vacías pueden requerir ajustes de formato más amplios, mientras que los errores suelen indicar problemas de infraestructura, como archivos que faltan, recursos bloqueados o dependencias nativas que faltan.
La lista de errores mantiene el contexto de cada archivo para facilitar el análisis de la causa raíz. En una tubería CI/CD, analice esta salida para establecer códigos de salida (cero para éxito completo y no cero cuando failCount es mayor que cero) o redirija los detalles del error a un sistema de alertas.
Para un mayor rendimiento, habilite el procesamiento paralelo configurando Multithreaded a true y ajustando MaxParallelThreads para coincidir con los núcleos CPU disponibles. Mantenga el aislamiento por archivo envolviendo la iteración paralela en Parallel.ForEach y usando una colección segura para hilos para la lista de errores.
Más información
- Tutoriales de IronBarcode: Leyendo códigos de barras: guías completas de lectura.
- Prevención de falsos positivos: reducción de lecturas fantasma en imágenes ruidosas.
- Guía de corrección de imágenes: filtros que mejoran la precisión de lectura.
- Guía de configuración de Docker: despliegue en contenedores con las dependencias nativas correctas.
- Referencia de API de BarcodeReaderOptions: documentación completa de configuración.
- Registro de cambios de IronBarcode: correcciones específicas de versión y adiciones de características.
Ver opciones de licencia cuando la tubería esté lista para producción.
Preguntas frecuentes
¿Cómo puedo manejar errores de código de barras en C# utilizando IronBarcode?
Puede manejar errores de código de barras en C# utilizando IronBarcode aprovechando su jerarquía de excepciones tipadas dentro del espacio de nombres IronBarCode.Exceptions. Esto le permite capturar excepciones específicas relacionadas con errores de archivo, contraseñas de PDF, problemas de codificación y más. Implementar un registro estructurado y usar las propiedades de BarcodeResult ayuda a diagnosticar y aislar problemas de manera eficiente.
¿Cuáles son algunas excepciones comunes lanzadas por IronBarcode?
IronBarcode puede lanzar varias excepciones, como IronBarCodeFileException para problemas relacionados con archivos, IronBarCodePdfPasswordException para PDFs protegidos con contraseña e IronBarCodeEncodingException para fallos de codificación. Cada tipo de excepción proporciona información de diagnóstico detallada para ayudar a resolver errores específicos encontrados durante el procesamiento de códigos de barras.
¿Cómo habilito el registro para diagnósticos en IronBarcode?
Para habilitar el registro para diagnósticos en IronBarcode, configure el modo de registro y la ruta del archivo usando IronSoftware.Logger antes de cualquier operación de código de barras. Esto captura los pasos de procesamiento interno y ayuda a rastrear problemas escribiendo registros en el archivo especificado.
¿Qué debo hacer si una operación de lectura de código de barras devuelve cero resultados en IronBarcode?
Si una operación de lectura de código de barras devuelve cero resultados en IronBarcode, indica que ningún código de barras coincidió con las opciones configuradas. Inspeccione sus parámetros y opciones de entrada, como ExpectBarcodeTypes y ReadingSpeed, y considere ampliar las expectativas de simbología o ajustar la velocidad de lectura para un escaneo más exhaustivo.
¿Puede IronBarcode manejar excepciones por dependencias nativas faltantes?
Sí, IronBarcode maneja excepciones por dependencias nativas faltantes a través de IronBarCodeNativeException. Puede filtrar estas excepciones para identificar DLLs faltantes o dependencias de plataforma, lo cual es particularmente útil en entornos Docker.
¿Cómo puedo depurar el procesamiento por lotes de códigos de barras con IronBarcode?
Para depurar el procesamiento por lotes de códigos de barras en IronBarcode, aísle cada operación de lectura en su propio bloque try-catch y capture los errores por archivo. Este enfoque asegura que la operación por lotes continúe a través de fallos y genere un resumen que incluya éxitos, fallos y resultados vacíos.
¿Cómo puedo capturar e interpretar excepciones de manera efectiva en IronBarcode?
Capture e interprete excepciones en IronBarcode ordenando sus bloques try-catch de específico a general. Comience con excepciones realizables como errores de archivo o problemas de contraseña de PDF y termine con la base IronBarCodeException para asegurar un manejo de errores exhaustivo.
¿Qué propiedades de BarcodeResult se pueden utilizar para el análisis post-mortem?
El objeto BarcodeResult en IronBarcode proporciona propiedades como BarcodeType, Value, PageNumber y Points (coordenadas) para el análisis post-mortem. Estas propiedades ayudan a entender resultados inesperados verificando el tipo de código de barras real versus el esperado y comprobando el número de página.
En IronBarcode, ¿cómo puedo prevenir falsos positivos durante las lecturas de códigos de barras?
Para prevenir falsos positivos durante las lecturas de códigos de barras en IronBarcode, puede usar filtros de imagen para mejorar la calidad de la imagen y la opción RemoveFalsePositive. Además, ajustar la velocidad de lectura y ExpectBarcodeTypes puede minimizar errores de fondos ruidosos.
¿Cómo maneja IronBarcode los errores de PDFs cifrados?
IronBarcode maneja los errores de PDFs cifrados utilizando la excepción IronBarCodePdfPasswordException. Para procesar dichos archivos, proporcione la contraseña utilizando PdfBarcodeReaderOptions o regístrelos y omítalos para un procesamiento de códigos de barras no disruptivo.
Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien estructurados y visualmente atractivos.