C# 读取文本文件并逐行处理

C# 读取文本文件并逐行处理,c#,c#-4.0,C#,C# 4.0,我有一个文本文件,我希望我的程序: 1-显示行数和文件路径 2-通过每条线循环 var lines = File.ReadLines(@"C:\\test.txt"); 编辑了答案 应该是这样的: string[] lines = File.ReadAllLines("....."); foreach (string line in lines) { if (line.StartsWith(

我有一个文本文件,我希望我的程序:

1-显示行数和文件路径

2-通过每条线循环

var lines = File.ReadLines(@"C:\\test.txt");                
编辑了答案


应该是这样的:

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

通过过滤包含名称ali的行,使其变得简单。 稍后,如果lines.count大于0,您可以使用foreach分割每一行

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

请显示代码中检查“ali”实际行的部分,循环在哪里?为什么。第一个默认值?你得到了所有的行,但只看第一个第一个默认值-为什么你期望它读得比第一行更多?这似乎是一个非常基本的问题,表明对该语言普遍缺乏知识,而不是一个具体的问题……谷歌教授很乐意告诉你c-sharp如何从文本文件中读取文本无需从ReadLines更改为ReadAllLines。事实上,ReadLines是首选的,因为它返回IEnumerable而不加载内存中的所有行。这是与大型客户合作时的一大优势files@Chris这是第一次注意到真的很抱歉,是的,我是一个初学者,但谢谢你的回答和你的建议time@ShannonHolsinger我在谷歌搜索了几个小时now@nabuchodonossor我确实试过foreach,但如果出现错误,它会出现一个错误:什么错误?哪一行代码?你把…换掉了吗。。。为您提供合适的值?通常,如果答案中包含对代码意图的解释,以及在不介绍其他代码的情况下解决问题的原因,那么答案会更有帮助。@Tomarnda这就是我使用注释来回答问题的原因,以帮助其他人理解不只是复制代码好的。这是有道理的。
var lines = File.ReadLines(@"C:\Test.txt").Where(l => l.Contains("ali"));
 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);
        }