如何在文本文件中上下移动项目

本文关键字:上下 移动 项目 文件 文本 | 更新日期: 2023-09-27 18:32:39

如何在文本文件中上下移动项目/值。目前我的程序读取文本文件,需要一段时间来确保当没有更多行要读取时它停止。我使用 if 语句来检查计数器是否等于我要移动的值的行。我被困住了,不知道如何从这里继续。

  _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++;
        }
    }

如何在文本文件中上下移动项目

您可以在内存中读取文件,将行移动到需要它的位置,然后写回文件。您可以使用 ReadAllLinesWriteAllLines

此代码将位置i处的字符串向上移动一行:

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);

@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)
    )
);