-1

I am coding for simple c# where I have to read from text file and display it in text box in format: Lastname, Firstname : EID “department” “designation”. The text file has data in format- EID,Firstname,Lastname,department,designation. Using readline memeber of streamreader class, and split into an array.

if(obj.ShowDialog() == DialogResult.OK)
{
filename = obj.FileName;
textBox1.Text = "";
string[] newline;
StreamReader reader = new StreamReader(filename, true);

while (reader.EndOfStream == false)
{
newline = reader.ReadLine().Split(',');
textBox1.Text = textBox1.Text + newline[1] + ", " + newline[2] + ": " + newline[0] + '"' + newline[3] + '"' +" " + '"' + newline[4] + '"'+"\n";

}
reader.Close();
}
Uyur99
  • 35
  • 1
  • 8

2 Answers2

1

You want a check on the length of the newline array:

if ( newline.Length >= 5 ) textBox1.Text = textBox1.Text + newline[1] + ", " + newline[2] + ": " + newline[0] + '"' + newline[3] + '"' +" " + '"' + newline[4] + '"'+"\n";

I also recommend you study up on using a "using" statement on your StreamReader, since its a disposable resource. That will ensure the file gets closed.

Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
0

I wanted to answer my question for others who might have same doubt.

if(obj.ShowDialog() == DialogResult.OK){
filename = obj.FileName;
textBox1.Text = "";             
StreamReader reader = new StreamReader(filename, true);
while (reader.EndOfStream == false)
{
string newline = reader.ReadLine();
{
string[] values = newline.Split(',');
textBox1.Text = textBox1.Text + values[1] + ", " + values[2] + ": " + values[0] + '"' + values[3] + '"' + " " + '"' + values[4] +'"' + Environment.NewLine;
}
}
reader.Close();
}
Uyur99
  • 35
  • 1
  • 8