Given this text data from a file:
Mehmet;Demirayak;IT
1
Emre;Araz;Sekten Chef
1
Nusret;Beganovic;Kein Geld
2
Ferhat;Acer;Acer Computer
2
Fevzi;Uzun;Trabzon
my goal is to read it using a StreamReader and store it in my defined class Personen.
If I had to split only one argument, it's not a problem. In other words, if the text in the file would be written only with the separator ";" and without any space or new line characters, I'd know how to read it. However, when I get a more complex structure in my data, such the one above, I am not sure how to read it.
This is why I have tried so far:
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++;
}
}
}
Based on the discussion in the comments under your question, in order to achieve your goal you can use the following logic for each line you read. If you indeed read '1' or '2', then skip the split operation for the current line and jump one iteration ahead by using
continue(thanks @PeterB for pointing out my mistake in the original answer). If not, then proceed to split the current line and store it intop:Also note that your statement
Console.WriteLine(p[i])is going to print only"Personen"which is not so meaningful. In order for it to print nicely the contents of the Personen object inp[i], you can override the methodToString()inclass Personen:Running the program and calling
read()produces the following output in the console:It's important to close the stream once you are done working with it, that's why I also added
usingin front of the instantiation ofStreamReader sr. See more about this at Do I need to explicitly close the StreamReader in C# when using it to load a file into a string variable?.