跳过行并从特定行开始读取 C# unity

Skip lines and start read from specific line C# unity

我正在读取一个文件,我正试图跳过前两行并从第三行开始读取。我已经检查了其他已回答的问题,但由于某种原因,其中 none 个问题在统一上起作用。我遇到了几个错误,但它应该可以工作。

StreamReader reader = new StreamReader(path);
string line = "";  

while ((line = reader.ReadLine()) != null)  
{
    string[] words = line.Split(' ');
    string type = words[0];
    float x = float.Parse(words[1]);
    ....
}

如果我没理解错的话,我们可以尝试使用File.ReadAllLines,它将return你文件文本中的所有文本内容,然后从第三行开始读取(数组从0开始,所以第三行可能是 contents[2]).

var contents = File.ReadAllLines(path);

for (int i = 2; i < contents.Length; i++)
{
    string[] words = contents[i].Split(' ');
    string type = words[0];
    float x = float.Parse(words[1]);
}

如果我们知道文件的 Encoding 我们可以尝试将 Encoding 设置为 File.ReadAllLines

中的第二个参数

类似于 D-Shih 的解决方案,是使用 File.ReadLines 的解决方案,其中 returns 和 IEnumerable<string>:

var lines = File.ReadLines(path);

foreach (string line in lines.Skip(2))
{
    string[] words = line.Split(' ');
    string type = words[0];
    float x = float.Parse(words[1]);
    // etc.
}

这种方法优于 D-Shih 的好处是您不必一次将整个文件读入内存来处理它,因此该解决方案类似于您现有解决方案对 StreamReader.


作为直接解决问题的解决方案,您只需要在进入循环之前调用 ReadLine 两次(跳过两行),尽管我认为上面的解决方案更清晰:

using (StreamReader reader = new StreamReader(path))
{
    string line = "";  
    
    // skip 2 lines
    for (int i = 0; i < 2; ++i)
    {
        reader.ReadLine();
    }

    // read file normally
    while ((line = reader.ReadLine()) != null)  
    {
        string[] words = line.Split(' ');
        string type = words[0];
        float x = float.Parse(words[1]);
        ....
    }
}

请注意,我还将 reader 包装在 using 中,以便在循环完成或抛出异常时关闭并处理文件句柄.