C# Escribir datos en un archivo CSV
-
Programa C# para escribir datos en un archivo
CSV
usando los métodos de la claseCsvHelper
-
C# Programa para escribir datos en un archivo
CSV
usando el métodoWriteAllText()

Los archivos CSV
son de gran utilidad para almacenar datos de forma organizada. Puedes escribir y leer datos desde y hacia un archivo CSV
usando diferentes lenguajes de programación.
En C# tenemos diferentes métodos para leer un archivo CSV y escribir los datos en un archivo CSV. Este artículo se centra en los diferentes métodos para escribir datos en un archivo CSV
.
Programa C# para escribir datos en un archivo CSV
usando los métodos de la clase CsvHelper
En C#, tenemos una biblioteca llamada CsvHelper
para leer y escribir archivos CSV
. Esta biblioteca no se proporciona por defecto. Más bien, tenemos que descargarla. Proporciona métodos como GetRecords
y WriteRecords
para leer y escribir un archivo CSV
. Esta es una biblioteca eficiente para leer y escribir archivos CSV
fácilmente.
El siguiente código de ejemplo muestra un programa que crea un file CSV
y escribe datos en él.
Código de ejemplo:
using System;
using System.IO;
using System.Text;
using CsvHelper;
namespace CsvExample
{
public class Project
{
public string PersonName { get; set; }
public string Title { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var data = new[]
{
new Project { CustomerName = "Olivia", Title = "Mother"},
new Project { CustomerName = "Lili", Title = "Elder Sister"}
};
using (var mem = new MemoryStream())
using (var writer = new StreamWriter(mem))
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.Configuration.Delimiter = ";";
csvWriter.Configuration.HasHeaderRecord = true;
csvWriter.Configuration.AutoMap<Project>();
csvWriter.WriteHeader<Project>();
csvWriter.WriteRecords(data);
writer.Flush();
var result = Encoding.UTF8.GetString(mem.ToArray());
Console.WriteLine(result);
}
}
}
}
Producción:
PersonName;Title
Olivia;Mother
Lili;Elder Sister
C# Programa para escribir datos en un archivo CSV
usando el método WriteAllText()
El método WriteAllText()
crea un archivo, escribe datos en el archivo y luego lo cierra. Si el archivo ya existe, entonces reescribe los datos en el archivo.
La sintaxis correcta para usar este método es la siguiente:
WriteAllText (StringPath, StringContents);
Código de ejemplo:
using System;
using System.IO;
using System.Text;
namespace CsvExample
{
public class Program
{
static void Main(string[] args)
{
string strFilePath = @"D:\New folder\Data.csv";
string strSeperator = ",";
StringBuilder sbOutput = new StringBuilder();
int[][] inaOutput = new int[][]{
new int[]{1000, 2000, 3000, 4000, 5000},
new int[]{6000, 7000, 8000, 9000, 10000},
new int[]{11000, 12000, 13000, 14000, 15000}
};
int ilength = inaOutput.GetLength(0);
for (int i = 0; i &lt; ilength; i++)
sbOutput.AppendLine(string.Join(strSeperator, inaOutput[i]));
// Create and write the csv file
File.WriteAllText(strFilePath, sbOutput.ToString());
// To append more lines to the csv file
File.AppendAllText(strFilePath, sbOutput.ToString());
}
}
}
Producción:
//CSV file created in the given directory
Da varias excepciones como ArgumentException
, ArgumentNullException
, PathTooLongException
, DirectoryNotFoundException
, IOException
y UnauthorizedAccessException
. Estas excepciones podrían ser manejadas usando un bloque try-catch
.