Zero
Zero

Reputation: 13

C# - Reading Text Files(System IO)

I would like to consecutively read from a text file that is generated by my program. The problem is that after parsing the file for the first time, my program reads the last line of the file before it can begin re-parsing, which causes it to accumulates unwanted data.


3 photos: first is creating tournament and showing points, second is showing text file and the third is showing that TeamA got more 3 points

   StreamReader = new StreamReader("Torneios.txt");

   torneios = 0;
   while (!rd.EndOfStream)
   {
       string line = rd.ReadLine();
       if (line == "Tournament") 
       { 
           torneios++;
       } 
       else 
       {
           string[] arr = line.Split('-');
           equipaAA = arr[0];
           equipaBB = arr[1];
           res = Convert.ToChar(arr[2]); 
       }
   }
   rd.Close();

That is what I'm using at the moment.

Upvotes: 0

Views: 87

Answers (1)

Samuel Allan
Samuel Allan

Reputation: 117

To avoid mistakes like these, I highly recommend using File.ReadAllText or File.ReadAllLines unless you are using large files (in which case they are not good choices), here is an example of an implementation of such:

string result = File.ReadAllText("textfilename.txt");

Regarding your particular code, an example using File.ReadAllLines which achieves this is:

string[] lines = File.ReadAllLines("textfilename.txt");
for(int i = 0; i < lines.Length; i++)
{
  string line = lines[i];
  //Do whatever you want here
}

Just to make it clear, this is not a good idea if the files you intend to read from are large (such as binary files).

Upvotes: 1

Related Questions