Home > Software design >  Skip lines and start read from specific line C# unity
Skip lines and start read from specific line C# unity

Time:05-29

I am reading from a file and I am trying to skip first two lines and start reading from the third one. I've checked other questions which were answered but none of them worked on unity for some reason. I get several errors however it should work.

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

CodePudding user response:

If I understand correctly, we can try to use File.ReadAllLines which will return all line of text content from your file text and then start reading on the third line (array start as 0, so that the third line might be 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]);
}

If we know the Encoding of the file we can try to set Encoding to the second parameter in File.ReadAllLines

CodePudding user response:

Similar to D-Shih's solution, is one using File.ReadLines, which returns an 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.
}

The benefit of this approach is that you don't have to read the entire file into memory at once to process it.


As a solution for directly fixing your problem, you just need to call ReadLine twice before getting into the loop (to skip the two lines), though I'd argue the solution above is more legible:

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

Notice that I've also wrapped the reader in a using, so that the file handle will be closed & disposed of once the loop completes, or in case of an exception being thrown.

  • Related