C# 如何在文本文件中向上/向下移动项目

C# 如何在文本文件中向上/向下移动项目,c#,.net,visual-studio,C#,.net,Visual Studio,如何在文本文件中上下移动项目/值。当我的程序读取一个文本文件时,an使用了一段时间来确保它在没有更多行可读取时停止。我使用if语句检查计数器是否等于我要移动的值的行。我不知道如何从这里继续下去 _upORDown = 1; using (StreamReader reader = new StreamReader("textfile.txt")) { string line = reader.ReadLine(); int Counter

如何在文本文件中上下移动项目/值。当我的程序读取一个文本文件时,an使用了一段时间来确保它在没有更多行可读取时停止。我使用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++;
        }
    }

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

此代码将
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);
if(i==0)返回;//无法向上移动第0行
string path=“c:\\temp\\myfile.txt”;
//接电话
string[]lines=File.ReadAllLines(路径);

如果(lines.Length@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)
    )
);

您可以读取文件替换值,然后重写旧版本将其写回。当计数器==\u upORDown时,您应该怎么做?您应该写入文件吗?您可以执行
while(!reader.EndOfStream)
而不是
while(line!=null)
您还应该执行
line=reader.ReadLine()
在循环中,否则您将陷入无限循环。@user1285872
i
是一个整数变量,设置为从零开始的行号,您希望将行号上移1。好的,谢谢,不断收到错误“错误1'System.Array'不包含'length'的定义,并且找不到接受'System.Array'类型的第一个参数的扩展方法'length'(是否缺少using指令或程序集引用?)”如果(lines.length@user1285872噢,你说得对,它应该是
length
,而不是
length
。谢谢,出现了另一个错误,“error 1 Operator”@user1285872
i
应该是
int