How to move items up / down in a text file

How to move items / values ​​up and down in a text file. At the moment, my program is reading a text file, but it takes some time to make sure it stops when there are no more lines to read. I used the if statement to check if the counter is equal to the string of the value I want to move. I'm stuck, not sure how to continue from here.

  _upORDown = 1; 

    using (StreamReader reader = new StreamReader("textfile.txt"))
    {
        string line = reader.ReadLine();
        int Counter = 1;
        while (line != null)
        {

            if (Counter == _upORDown)
            {
              //Remove item/replace position

            }
            Counter++;
        }
    }
+5
source share
2 answers

You can read the file in memory, move the line to where you need it, and write the file back. You can use ReadAllLinesand WriteAllLines.

This code moves the line iup one line:

if (i == 0) return; // Cannot move up line 0
string path = "c:\\temp\\myfile.txt";
// get the lines
string[] lines = File.ReadAllLines(path);
if (lines.Length <= i) return; // You need at least i lines
// Move the line i up by one
string tmp = lines[i];
lines[i] = lines[i-1];
lines[i-1] = tmp;
// Write the file back
File.WriteAllLines(path, lines);
+3

@dasblinkenlight , LINQ:

string path = "c:\\temp\\myfile.txt";
var lines = File.ReadAllLines(path);
File.WriteAllLines(
    path,
    lines.Take(i).Concat(
        lines.Skip(i+1)
    )
);

i ( ) .

:

string path = "c:\\temp\\myfile.txt";
var lines = File.ReadAllLines(path);
var newline = "New line here";
File.WriteAllLines(
    path,
    lines.Take(i).Concat(
        new [] {newline}
    ).Concat(
        lines.Skip(i+1)
    )
);
0

All Articles