I want to duplicate a line from a text file (.txt) and insert it above the line selected when a button is clicked
eg:
Tomato
Lemon
Apple
and I want to duplicate "Lemon" and insert it above when I click a button, like :
Tomato
Lemon
Lemon <- Inserted Line
Apple
I've tried :
C#
void duplLine(string pathFile, int line)
{
List tempFile = File.RealAllLines(pathFile).ToList();
tempFile.Add(tempFile[line]);
File.writeAllLines(pathFile, tempFile.ToArray();
}It worked perfectly but the line was inserted at the END like :
Tomato
Lemon
Apple
Lemon <- Inserted Line (This should be at the index 2)
Thanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 16, 2023, 2:21 AM EST
Hello Haga,
Try to use List.Insert instead of
List.Addmethod.Example:
void duplLine(string pathFile, int line) { List tempFile = File.ReadAllLines(pathFile).ToList(); tempFile.Insert(line, tempFile[line]); File.WriteAllLines(pathFile, tempFile.ToArray()); }Thanks
Naimish Makwana
Haga Andrianavalona20 reputationPosted Feb 16, 2023, 2:32 AM EST
thanks Naimish Makwana, It worked perfectly.