79 lines
2.6 KiB
C#
79 lines
2.6 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
using NDbfReader;
|
|
|
|
namespace S7Explorer.Parsers
|
|
{
|
|
public class DbfParser
|
|
{
|
|
// Lee campos específicos de un archivo DBF
|
|
public static List<Dictionary<string, string>> ReadDbfFile(string filePath, IEnumerable<string> fieldNames)
|
|
{
|
|
var result = new List<Dictionary<string, string>>();
|
|
|
|
if (!File.Exists(filePath))
|
|
throw new FileNotFoundException($"No se encontró el archivo DBF: {filePath}");
|
|
|
|
try
|
|
{
|
|
// Abrir tabla DBF con codificación específica
|
|
using var stream = File.OpenRead(filePath);
|
|
using var table = Table.Open(stream);
|
|
|
|
// Crear lector usando la API correcta
|
|
var reader = table.OpenReader();
|
|
|
|
while (reader.Read())
|
|
{
|
|
var record = new Dictionary<string, string>();
|
|
|
|
foreach (var fieldName in fieldNames)
|
|
{
|
|
// Obtener valor y convertir a string si no es null
|
|
var value = reader.GetValue(fieldName);
|
|
record[fieldName] = value?.ToString() ?? string.Empty;
|
|
|
|
// Manejamos específicamente bytes para campos como "MC5CODE"
|
|
// que pueden contener datos binarios codificados como CP1252
|
|
if (value is byte[] byteValue)
|
|
{
|
|
record[fieldName] = Encoding.GetEncoding(1252).GetString(byteValue);
|
|
}
|
|
}
|
|
|
|
result.Add(record);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new Exception($"Error al leer el archivo DBF {filePath}: {ex.Message}", ex);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
// Convierte un string que representa un número a un entero opcional
|
|
public static int? StringToInt(string value)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(value))
|
|
return null;
|
|
|
|
if (int.TryParse(value, out int result))
|
|
return result;
|
|
|
|
return null;
|
|
}
|
|
|
|
// Convierte códigos Windows-1252 a UTF-8 para manejar caracteres especiales en STEP7
|
|
public static string ConvertCP1252ToUtf8(string input)
|
|
{
|
|
if (string.IsNullOrEmpty(input))
|
|
return string.Empty;
|
|
|
|
byte[] bytes = Encoding.GetEncoding(1252).GetBytes(input);
|
|
return Encoding.UTF8.GetString(bytes);
|
|
}
|
|
}
|
|
} |