use*_*872 5 .net c# visual-studio
如何在文本文件中上下移动项目/值.目前我的程序读取文本文件,使用一段时间确保在没有更多行要读取时停止.我使用if语句来检查counter是否等于我想要移动的值的行.我不知道怎么从这里继续.
_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++;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以读取内存中的文件,将行移动到需要的位置,然后将文件写回。您可以使用ReadAllLines和WriteAllLines。
此代码将位置上的字符串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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
775 次 |
| 最近记录: |