How to change row in text file in C #?

1

I currently report on the variable stringantiga the exact value to find and replace it.

Is there any way to substitute for the line number instead of the exact value of stringantiga ?

string arquivo = ConfigurationSettings.AppSettings["Caminho"].ToString();
string stringbusca = "MaxChannelInUse";
string stringantiga = "MaxChannelInUse=80";
string stringnova = "MaxChannelInUse=90000";
StreamReader sr = new StreamReader(arquivo);
StringBuilder sb = new StringBuilder();

while (!sr.EndOfStream)
{
    string s = sr.ReadLine();
    if (s.IndexOf(stringbusca) > -1)
    {
        s = s.Replace(stringantiga, stringnova);
    }
    sb.AppendLine(s);
}
sr.Close();

StreamWriter sw = new StreamWriter(arquivo);
sw.Write(sb);

sw.Close();
    
asked by anonymous 16.02.2018 / 16:03

1 answer

0

Yes. You can simply read the entire file by using the File.ReadAllLines() / strong> , change the line and then write to the file using the File.WriteAllLines() .

var arquivo = ConfigurationSettings.AppSettings["Caminho"].ToString();
var linhas = File.ReadAllLines(arquivo);

arquivo[0] = "Novo conteúdo"; // Editar a primeira linha

File.WriteAllLines(arquivo, linhas);
    
16.02.2018 / 16:08