Edit text file in a specific line [closed]

0

I have a txt file that tells me 3 fields: error line, wrong number and number to replace.

But I'm not thinking of an instruction to go directly to the line I need, this file follows a layout.

I can put the examples here, if you like.

link

asked by anonymous 14.06.2018 / 20:51

1 answer

0

Before following the code, you have to know which line you want to edit, in the example below I put it in line 1 :

 int line_to_edit = 1; //linha 1
 string newText = "|C425|1033395|4,000|CX|12,15|0,20|0,91|";
 string path = "colocar o caminho do arquivo";
 string[] arrLine = File.ReadAllLines(path);
 arrLine[line_to_edit - 1] = newText;
 File.WriteAllLines(path, arrLine);

Original answer: StackOverFlow English

Update:

//arquivo logs
string[] logs = File.ReadAllLines(@"C:\logs.txt");

//arquivo para modificar
string path = @"C:\modificar.txt";
string[] arrLine = File.ReadAllLines(path);

foreach (var item in logs)
{
    //split[0] = LINHA
    //split[1] = VALOR ERRADO
    //split[2] = VALOR A SUBSTITUIR
    var split = item.Split('|');
    int line_to_edit = Convert.ToInt32(split[0]);
    var replace = arrLine[line_to_edit - 1].Replace(split[1], split[2]);
    string newText = replace;
    arrLine[line_to_edit - 1] = newText;
    File.WriteAllLines(path, arrLine);
}
    
14.06.2018 / 21:08