如何为文本文件中的每一行创建一个数组?

How do I create an array of each line in a text file?

我是 C# 新手! 每当我想在其他程序中解析 .txt 文件中的信息时,我都会创建一个循环来读取整个文件并将每一行保存为以该文件命名的数组。我不知道如何在 C# 中执行此操作并寻求帮助,这是我的过程示例:

//This is not a programming language, just my thought process on how it works;

loop
{
    ReadFile "File1.txt", Line i, save as vTempLine
    if (vTempLine != null)
    {
        vCount = i
        vFile1Array[i] = vTempLine
    }
    else
    {
        vCountLoop1 = vCount
        vTempLine = ""
        vCount = ""
        Break
    }
}

我来自AutoHotkey,这是一个小例子。基本上:

  1. 循环重复直到中断

  2. 第一个命令一次读取一个.txt文件一行,告诉读取第i行,这是当前循环的行。将此行保存为变量字符串 vTempLine.

  3. 检查以确保该行存在,然后将当前行数保存为vCount,将当前行保存为vFile1Array,其中当前数组数等于环形。这样每个数组编号都等于它形成的行(跳过起始数组变量 0)。

  4. 如果读取的文件中的行不存在,则假定文件结束并将临时变量保存到长期变量中,然后关闭这些临时变量并中断循环。

  5. 最终结果将有两个变量,一个名为vCountLoop1,其中包含文件中的行数。

  6. 第二个变量是一个数组,每个数组变量存储为文本文件中的一行(跳过数组 0 的存储)。

这段代码不是很好,但你在考虑类似的事情吗?

string vTempLine;    // Not needed to be declared outside the loop
int i = 0;
int vCountLoop1 = 0; // Not needed: Might be the same as i
Dictionary<int, string> vFile1Array = new Dictionary<int, string>(); // Or use a List<string>

using (StreamReader sr = new StreamReader("File1.txt")) 
{
    while (sr.Peek() >= 0) 
    {
        // if statement is not needed here
        i++;
        vTempLine = sr.ReadLine();
        vCountLoop1 = i;
        vFile1Array[i] = vTempLine; 
    }
}