将文本文件行读入数组
我有两个文本框.
我有一个文本文件,其中包含我们网络上使用的不同脚本的文件路径列表.
该文件的设置如下:
C:\ Scripts \ dnsflush.ps1
C:\ Scripts \ DFQ.ps1
D:\ N \ Exchange \ Netservicestop.ps1
D:\ AD \ scripts \ ugroups.ps1
我只想阅读"C:\ Scripts \ dnsflush.ps1" -line0和"D:\ N \ Exchange \ Netservicestop.ps1" -line2行,然后将其作为字符串打印到表单上的文本框.
Hi,
i have two textboxes.
I have a text file that has list of file paths for different scripts used on our network.
the file is setup like this:
C:\Scripts\dnsflush.ps1
C:\Scripts\DFQ.ps1
D:\N\Exchange\Netservicestop.ps1
D:\AD\scripts\ugroups.ps1
i want to only read the lines "C:\Scripts\dnsflush.ps1" -line0 and "D:\N\Exchange\Netservicestop.ps1" -line2 and then iwant to print the line to textbox on the form as a string.
foreach (string line in File.ReadLines("c:\\file.txt"))
{
textbox1.text = (line0);
textbox2.text = (line2);
}
我不知道从哪里开始可以提供任何帮助:)
i have no idea where to start any help would be great :)
一种解决方法是;
One way of doing it is;
string filename = "yourtextfilepath.txt";
if (File.Exists(filename))
{
string[] lines = File.ReadAllLines(filename);
Console.WriteLine(lines["the line number that you want to print - 1"]);
}
如果您不想阅读所有行,这是另一种解决方案,但是您必须阅读所有前一行,直到找到所需的行号:
If you dont want to read all the lines here is another solution but you have to read all the previous line till to the desired line number:
string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName)) {
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}
祝你好运,
OI
Good luck,
OI