0

I want to find out the line of where the string exist in the text file and then change the line with another string

var location = "bla bla bla";
string fileContents = File.ReadAllText(location);
if (fileContents.Contains("LastSession\tcallsign"))
{
    // here i want to save the line info of the "LastSession\tcallsing into a string variable then replace the string with another string
}

ravenaxd
  • 13
  • 2

1 Answers1

1

You could use:

StringComparison comparison = StringComparison.Ordinal; // change to OrdinalIgnoreCase if desired
string searchString = "LastSession\tcallsign";
string replaceString = "new value";

var newLines = File.ReadLines(location)
    .Select(GetNewLineInfo)
    .Select(x => x);
    
// if you want to know the line-numbers
var matchLineNumbers = newLines.Where(x => x.Contains).Select(x => x.LineNumber);

// if you want to rewrite the file with the new lines:
File.WriteAllLines(location, newLines.Select(x => x.NewLine));

(bool Contains, string NewLine, int LineNumber) GetNewLineInfo(string line, int index)
{
    bool contains = line.IndexOf(searchString, comparison) >= 0;
    return (contains, contains ? line.Replace(searchString, replaceString) : line, index + 1);
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939