I need help with my c# code

hey, i want to save this text in my code, but it doesnt work. i dont know how i can change my code so, that i read more as the first line.

Mehmet;Demirayak;IT
1
Emre;Araz;Sekten Chef
1
Nusret;Beganovic;Kein Geld
2
Ferhat;Acer;Acer Computer
2
Fevzi;Uzun;Trabzo

and thats my code

public void read()
{
StreamReader sr = new StreamReader(datei);
string s;

  int i = 0;
  while ((s = sr.ReadLine()) != null)
  {
          string[] l = s.Split(";");
      if(s.StartsWith("1") || s.StartsWith("2"))
      {
          p[i] = new Personen(l[0], l[1], l[2]);
          Console.WriteLine(p[i]);
          i++;
      }
  }

}

You are along the right lines here. However, with the snippet you supplied you never open a file from which to read data. The StreamReader class takes a Stream object as a parameter in its constructor. I assume that “datei” is the files you want to read from. You can conver the file into a stream by using File.Open(). Here is an example which you can play around with to fit your needs:

void read()
{
    string folder = "your//folder//path//here"; // eg "C:\\Users\\Default\\Documents"
    string fileName = "datei.txt";

    FileStream stream = File.Open(Path.Combine(folder, fileName), FileMode.Open);

    StreamReader sr = new StreamReader(stream);
    string? s;

    while ((s = sr.ReadLine()) != null)
    {
        string[] l = s.Split(";");
        if (l[0] == "1" || l[0] == "2")
        {
            Console.WriteLine("FirstName: {0}, SecondName: {1}, ThirdName:{2}", l[1], l[2], l[3]);
        }
    }
}

read();

To make this work I had to change the data structure of your input file “datei.txt” to the following:

1;Mehmet;Demirayak;IT
1;Emre;Araz;Sekten Chef
2;Nusret;Beganovic;Kein Geld
2;Ferhat;Acer;Acer Computer
2;Fevzi;Uzun;Trabzo

Hope this helps :slight_smile:

1 Like