我尝试编写一个脚本,按行读取TXT文件,并根据其内容更改标签。
是否有一种方法可以检查正在读取哪一行?
我尝试编写一个脚本,按行读取TXT文件,并根据其内容更改标签。
是否有一种方法可以检查正在读取哪一行?
这个例子使用 StreamReader 类的 ReadLine 方法,以字符串的形式逐行读取文本文件内容,并且您可以检查该行字符串是否匹配您想要的标签,然后替换成目标标签。
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine(line);
counter++;
}
file.Close();
System.Console.WriteLine("There were {0} lines.", counter);
System.Console.ReadLine();
或者
using System;
using System.IO;
public class Example
{
public static void Main()
{
string fileName = @"C:\some\path\file.txt";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
希望这能帮到你。
file.Close();
,而是将其包装在 using 中:using (file = new StreamReader(@"c:\test.txt")) {...}
- Dmitry Bychenko using System.IO;
using System.Linq;
...
var modifiedLines = File
.ReadLines(@"c:\myInitialScript.txt") // read file line by line
.Select((line, number) => {
//TODO: relevant code here based on line and number
// Demo: return number and then line itself
return $"{number} : {line}";
})
// .ToArray() // uncomment if you want all (modified) lines as an array
;
如果您想将修改后的行写入文件:
File.WriteAllLines(@"c:\MyModifiedScript.txt", modifiedLines);
StreamReader
,你可以实现一个 for
循环: using (StreamReader reader = new StreamReader("c:\myInitialScript.txt")) {
for ((string line, int number) record = (reader.ReadLine(), 0);
record.line != null;
record = (reader.ReadLine(), ++record.number)) {
//TODO: relevant code here
// record.line - line itself
// record.number - its number (zero based)
}
}
StreamReader
必须实现它。它只做它设计的事情 - 按需读取。 - Alexey LarionovFile.ReadLines(...)
和 Linq,例如File.WriteAllLines(@"c:\myNewText.txt" File.ReadLines(@"c:\myText.txt").Select((line, number) => /*相关代码在此*/));
- Dmitry Bychenko