Last active
August 29, 2015 14:11
-
-
Save greivinlopez/8eb802bc1053b9481fa1 to your computer and use it in GitHub Desktop.
Ejemplo de modificación de un archivo de registros con campos separados por ";"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String path = @"C:\file.txt"; | |
List<String> lines = new List<String>(); | |
// Acá van las constantes para las posiciones de los campos | |
public const int NAME = 0; | |
public const int WORK = 1; | |
public const int ID = 2; | |
if (File.Exists(path)); | |
{ | |
// Acá se crea un reader para leer el archivo | |
using (StreamReader reader = new StreamReader(path)) | |
{ | |
String line; | |
// Se lee el archivo línea por línea | |
while ((line = reader.ReadLine()) != null) | |
{ | |
if (line.Contains(";")) | |
{ | |
// Se separa el registro en un arreglo | |
String[] split = line.Split(';'); | |
// Se analiza lo que se quiere cambiar | |
if (split[NAME].Contains("danny")) | |
{ | |
// Se hace el cambio | |
split[NAME] = "papi"; | |
line = String.Join(";", split); | |
} | |
} | |
// Se van guardando las líneas incluyendo las modificadas | |
lines.Add(line); | |
} | |
} | |
// Y acá se crea el writer para escribir todas las líneas de nuevo pero modificadas | |
using (StreamWriter writer = new StreamWriter(path, false)) | |
{ | |
foreach (String line in lines) | |
writer.WriteLine(line); | |
} | |
} |
Ok hay varias cosas que cambiar en tu codigo:
- Ponele el .Close al primer using "LineasLeer.Close"
- Los nombres de las constantes deberían ser todo mayúscula y sin el "_" adelante> _Nombre -> NOMBRE. Incluso yo lo cambiaría a POSICION_NOMBRE para hacerlo más legible y explícito.
- Los nombres de los parámetros deberían estar en minuscula: Nombre -> nombre
- Un buen código no debería tener nombres en español (solo inglés). Si igual lo vas a poner en español todos los identificadores deben ir en español o sea cambia "lines" por "lineas". Y "LineasLeer" podria llamarse "lineaActual".
- Tu problema puede estar fuera de ese método, en el resto del código si se abre el mismo archivo y no se cierra correctamente o incluso si hay procesos corriendo anteriormente que no liberaron el archivo de forma correcta (incluso una corrida anterior del mismo programa)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GreivinLopez: Este es el método completo que cree, recibe varios por párametro algunos valores y esos son los que uso para modificar el archivo, pero me da un error al ejecutar.
public void ModificarRegistros (string Nombre, string cargo ,string Direccion, string email,
string Organizacion,string Skype, string telefono)
{
List lines = new List();
string path = @"C:\archivo_proyecto.txt";
const int _Nombre = 0;
const int _Organizacion= 1;
const int _Cargo = 4;
const int _email = 5;
const int _skype = 2;
const int _telefono = 6;
const int _direccion = 3;