Code explanation - C#

continuation of this

Hi. In my last question (2) I was provided a piece of code that can read text documents. It is excactly what I need for my project, but the comments on the code wasnt really that descriptive (no offense @Drakestar). So I was wondering if there was anyone that would help me out and explain me what variables I need to edit to read the (example:) 4th line of a file located at “C:/MyGame/data/document.txt”

-thanks :slight_smile:

EDIT: here’s the code:

using System.Text;
using System.IO;  

private bool Load(string fileName)
{
    // Handle any problems that might arise when reading the text
    try
    {
        string line;
        // Create a new StreamReader, tell it which file to read and what encoding the file
        // was saved as
        StreamReader theReader = new StreamReader(fileName, Encoding.Default);

        // Immediately clean up the reader after this block of code is done.
        // You generally use the "using" statement for potentially memory-intensive objects
        // instead of relying on garbage collection.
        // (Do not confuse this with the using directive for namespace at the 
        // beginning of a class!)
        using (theReader)
        {
            // While there's lines left in the text file, do this:
            do
            {
                line = theReader.ReadLine();

                if (line != null)
                {
                    // Do whatever you need to do with the text line, it's a string now
                    // In this example, I split it into arguments based on comma
                    // deliniators, then send that array to DoStuff()
                    string[] entries = line.Split(',');
                    if (entries.Length > 0)
                        DoStuff(entries);
                }
            }
            while (line != null);

            // Done reading, close the reader and return true to broadcast success    
            theReader.Close();
            return true;
            }
        }

        // If anything broke in the try block, we throw an exception with information
        // on what didn't work
        catch (Exception e)
        {
            Console.WriteLine("{0}

", e.Message);
return false;
}
}
}

You could read the whole file into a list and then you could access any line you like:

  import System.Collections.Generic;
 import System.Linq;
  import System.IO;

  var fileLines : List.<String>;

  function ReadFile() {
     var sr = File.OpenText("whatever.txt");
     fileLines = sr.ReadToEnd().Split("

"[0]).ToList();
sr.Close();
}

Now you have a list of lines that you can insert into, get a specific line from - whatever. If you want to write them back out you can just do:

 var wholeFileText = String.Join("

", fileLines.ToArray());

To get line 4 you just do fileLines[3].