Something like this should work (Insert within a function) :
try
{
Contenido = File.ReadAllText("Ruta/De/Mi/Csv");
File.WriteAllText("Mi/Nueva/Ruta/Del/Csv", Contenido.Replace(",", "|")
}
catch
{
Console.WriteLine("Ha habido un error de E/S"); // Comentar si no es una aplicación de consola.
MessageBox.Show("Ha habido un error de E/S"); // Comentar si es un Windows Forms o algo por el estilo.
}
The try/catch
I have set for error handling, you may try to open a non-existent file and launch one or more Exception
.
Remember to do using System.IO;
to be able to use class File
.
Anti-quotation method, Version 2
Fixes:
- The only way to replace commas as separators.
- Do not save the file automatically when you finish your work.
In case of reading error returns null
and in case of writing error returns the string
modified to avoid losing processed data.
This other method is responsible for replacing the values of a ... Best form ?
Considering that the contents of your csv have commas inside values with quotes, with the previous solution they would also be replaced, so it is necessary to know the exact position of the quotes to ignore them:
public string ReemplazarComasCSV(string direccion, char delim, char newdelim) {
string Contenido = "";
string Salida = "";
char Comilla = 'yo,tu,el,"nosotros somos"
si,bien,"contenido",'nope'
';
try {
Contenido = File.ReadAllText(direccion);
}
catch { return null; }
for (int i = 0; i < Contenido.Length; i++) {
if (Contenido[i] == delim)
Salida += newdelim;
else if (Contenido[i] == '"' || Contenido[i] == '\'' || Contenido[i] == ''') {
Comilla = Contenido[i]; Salida += Comilla;
++i;
while ((i < Contenido.Length) && (Contenido[i] != Comilla)) {
Salida += Contenido[i]; i++;
}
Salida += Comilla;
}
else {
Salida += Contenido[i];
}
}
try {
File.WriteAllText(direccion, Salida);
}
catch { /* Arroja algun error :) */ }
return Salida;
}
What this last method does is that it ignores the values that are in quotes of type: ""
, ''
and '
in order to leave the values completely in order, I have tested it with the following content in a csv:
try
{
Contenido = File.ReadAllText("Ruta/De/Mi/Csv");
File.WriteAllText("Mi/Nueva/Ruta/Del/Csv", Contenido.Replace(",", "|")
}
catch
{
Console.WriteLine("Ha habido un error de E/S"); // Comentar si no es una aplicación de consola.
MessageBox.Show("Ha habido un error de E/S"); // Comentar si es un Windows Forms o algo por el estilo.
}
Note: The new method uses 3 arguments, the first is the address of the csv, the second is the delimiter and the third is the new delimiter.
References:
Greetings:)