I tried making a script that would read a TXT file line by line, and change labels depending on what is inside. Is there a way to check which line is being read?
I tried making a script that would read a TXT file line by line, and change labels depending on what is inside. Is there a way to check which line is being read?
This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class and you can just check the line string and matches with your desire label and replace with that.
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();
OR
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);
}
}
}
}
Hope this will help you.
You can try querying file with a help of Linq:
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
;
If you want write modified lines to a file:
File.WriteAllLines(@"c:\MyModifiedScript.txt", modifiedLines);
If you insist on StreamReader, you can implement a for loop:
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)
}
}