我有一个文本文件,我希望我的程序:
1 - 显示行数和文件路径。
2 - 遍历每一行。
var lines = File.ReadLines(@"C:\\test.txt");
已编辑(答案)
public static string[] local_file; // make a string array to load the file into it
int i = 0; // index of lines
try
{
OpenFileDialog op = new OpenFileDialog // use OpenFileDialog to choose your file
{
Filter = "Combos file (*.txt)|*.txt" ;// select only text files
}
if (op.ShowDialog() == DialogResult.OK)
{
local_file= File.ReadAllLines(op.FileName);// load all the contents of the file into the array
string count = "lines = " + Convert.ToString(local_file.Length); // number of lines
string file_name = op.FileName; // show the file name including the path
}
for (i; i < local_file.Length; i++)// loop through each line
{
// do something here remember to use local_file[i] for the lines
}
}catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
答案 0 :(得分:3)
通过过滤包含名称ali的行来轻松实现。 稍后,如果lines.count大于0,您可以使用foreach来拆分每一行。
var lines = File.ReadLines(@"C:\Test.txt").Where(l => l.Contains("ali"));
答案 1 :(得分:0)
应该是这样的:
string[] lines = File.ReadAllLines(".....");
foreach (string line in lines)
{
if (line.StartsWith("...."))
{
}
}
答案 2 :(得分:0)
您可以使用LINQ:
完成所有操作var parts = File.ReadLines(@"C:\test.txt") // No need to escape backslash here since you're using a verbatim string
.Select(line => line.Split(':'))
.FirstOrDefault(p => p.Length == 2 && p[0] == "ali");
if (parts != null)
{
textBox1.Text = parts[0];
textBox2.Text = parts[1];
}
答案 3 :(得分:0)
public static string[] local_file; // make a string array to load the file into it
int i = 0; // index of lines
try
{
OpenFileDialog op = new OpenFileDialog // use OpenFileDialog to choose your file
{
Filter = "Combos file (*.txt)|*.txt" ;// select only text files
}
if (op.ShowDialog() == DialogResult.OK)
{
local_file= File.ReadAllLines(op.FileName);// load all the contents of the file into the array
string count = "lines = " + Convert.ToString(local_file.Length); // number of lines
string file_name = op.FileName; // show the file name including the path
}
for (i; i < local_file.Length; i++)// loop through each line
{
// do something here remember to use local_file[i] for the lines
}
}catch (Exception exception)
{
MessageBox.Show(exception.Message);
}