How to change line in text file in C#?

Asked

Viewed 2,080 times

1

Currently I inform in 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();

1 answer

1


Yes. You can simply read the entire file using the method File.ReadAllLines(), change the line and then write to the file using the method 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);
  • For example, if by chance someone enters my text file and deletes one of the lines. Is there any other way to find that specific value in my example (stringantiga= "Maxchannelinuse") ?

  • @Gabrielsant'Ana Certainly not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.