For starters, get rid of labels and
goto
- you should use a loop construct like
for
or
while
instead. In fact, forget
goto
even exists for a couple of years - by then you will understand when it is appropriate, which in almost never in "normal" code.
You also should never use Convert methods on user input - they make mistakes, and it's kinda annoying when your app crashes because of a miskey.
int id;
while (true)
{
Console.Write("Enter ID: ");
if (int.TryParse(Console.ReadLine(), out id))
{
break;
}
Console.WriteLine($"\"{val}\" is not a valid integer.");
}
Is a lot more friendly!
Write a method that takes four parameters:
private static void WriteLine(StreamWriter sw, int id, string name, float salary)
{
}
And make it write the values to the stream. That way, it's more "organised" and clearer to read. And trivial:
StreamWriter
has a
WriteLine
method.
Then reading back is pretty simple too - just loop through the file until it runs out of data, and read each item back. Use the same
TryParse
code to convert teh values and it's pretty easy.