How to load text file into a textbox in .net

This example shows that how to load text file into textbox control.

Following example requires two textbox control and one button. when user select text file with the help of button named ‘Button1Browse’ then textbox1 will show content of that text file. before applying code you need to set multi-line Property to ‘True’ and set scroll-bar to ‘Vertical’ of Textbox1 control.

[VB.Net]

Private Sub Button1Browse_Click(ByVal sender As System.Object, _
  1.             ByVal e As System.EventArgs) Handles Button1Browse.Click
  2.  
  3.         Dim openFileDialog1 As System.Windows.Forms.OpenFileDialog
  4.         openFileDialog1 = New System.Windows.Forms.OpenFileDialog()
  5.         openFileDialog1.Filter = "Text file|*.txt"
  6.  
  7.         If openFileDialog1.ShowDialog() = DialogResult.OK Then
  8.             Try
  9.                 txtSelectedFilepath.Text = openFileDialog1.FileName
  10.                 Dim srRead As New System.IO.StreamReader(openFileDialog1.FileName)
  11.                 Dim strFileText As String = ""
  12.                 strFileText = srRead.ReadToEnd
  13.                 srRead.Close()
  14.                 TextBox1.Text = strFileText
  15.  
  16.             Catch ex As Exception
  17.                 MessageBox.Show(ex.Message)
  18.             End Try
  19.         End If
  20.     End Sub

[C#.Net]

private void Button1Browse_Click(System.Object sender, System.EventArgs e)
  1.         {
  2.             System.Windows.Forms.OpenFileDialog openFileDialog1 = null;
  3.             openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
  4.             openFileDialog1.Filter = "Text file|*.txt";
  5.  
  6.             if (openFileDialog1.ShowDialog() == DialogResult.OK)
  7.             {
  8.                 try
  9.                 {
  10.                     txtSelectedFilepath.Text = openFileDialog1.FileName;
  11.                     System.IO.StreamReader srRead = new System.IO.StreamReader(openFileDialog1.FileName);
  12.                     string strFileText = "";
  13.                     strFileText = srRead.ReadToEnd();
  14.                     srRead.Close();
  15.                     TextBox1.Text = strFileText;
  16.  
  17.                 }
  18.                 catch (Exception ex)
  19.                 {
  20.                     MessageBox.Show(ex.Message);
  21.                 }
  22.             }
  23.         }