读取文本文件并逐行处理

本文关键字:逐行 处理 文件 取文本 读取 | 更新日期: 2023-09-27 18:06:45

我有一个文本文件,我想让我的程序:

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);
    }

读取文本文件并逐行处理

通过过滤包含name ali的行来简化。稍后,您可以使用foreach将每一行拆分为几行。Count大于0

var lines = File.ReadLines(@"C:'Test.txt").Where(l => l.Contains("ali"));

应该看起来像这样:

        string[] lines = File.ReadAllLines(".....");
        foreach (string line in lines)
        {
            if (line.StartsWith("...."))
            { 
            }
        }

您可以使用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];
}
 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);
        }