I’m trying to move line in a text file up by one then rewrite it back to the original file, but getting error for some reason, can’t seem to figure it out.
using (StreamReader reader = new StreamReader("file.txt"))
{
string line;
int Counter = 0;
while ((line = reader.ReadLine()) != null)
{
string filepath = "file.txt";
int i = 5;
string[] lines = File.ReadAllLines(filepath);
if (lines.Length >= i)
{
string tmp = lines[i];
lines[i] = lines[i-1];
lines[i-1] = tmp;
File.WriteAllLines(filepath, lines);
}
}
Counter++;
}
I assume that you actually want to swap each line(?) in the file, because of this code snippet:
So here’s an approach that should work:
Edit: Here’s the slightly modified version that swaps only one line with it’s previous line, since you’ve commented that this is your requirement: