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, _
            ByVal e As System.EventArgs) Handles Button1Browse.Click
 
        Dim openFileDialog1 As System.Windows.Forms.OpenFileDialog
        openFileDialog1 = New System.Windows.Forms.OpenFileDialog()
        openFileDialog1.Filter = "Text file|*.txt"
 
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                txtSelectedFilepath.Text = openFileDialog1.FileName
                Dim srRead As New System.IO.StreamReader(openFileDialog1.FileName)
                Dim strFileText As String = ""
                strFileText = srRead.ReadToEnd
                srRead.Close()
                TextBox1.Text = strFileText
 
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
        End If
    End Sub

[C#.Net]

        private void Button1Browse_Click(System.Object sender, System.EventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFileDialog1 = null;
            openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "Text file|*.txt";
 
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    txtSelectedFilepath.Text = openFileDialog1.FileName;
                    System.IO.StreamReader srRead = new System.IO.StreamReader(openFileDialog1.FileName);
                    string strFileText = "";
                    strFileText = srRead.ReadToEnd();
                    srRead.Close();
                    TextBox1.Text = strFileText;
 
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }