How to read text file (*.txt) in C#
By FoxLearn 11/22/2024 7:45:25 AM 12.85K
How to read text file in C#?
Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ReadTxtFile" and then click OK
Drag and drop the TextBox, Button controls from the Visual Toolbox onto your form designer, then design your form as shown below.
Add a click event handler to the Open button to allow opening a text file and displaying its content in the TextBox control as shown below.
private async void btnOpen_Click(object sender, EventArgs e) { try { // Open file dialog to select a text file using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text Documents|*.txt", Multiselect = false, ValidateNames = true }) { if (ofd.ShowDialog() == DialogResult.OK) { using (StreamReader sr = new StreamReader(ofd.FileName)) { txtValue.Text = await sr.ReadToEndAsync(); } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
StreamReader.ReadToEndAsync
is used for non-blocking reading of the file contents. This ensures the UI remains responsive while reading large files.
This is an example of asynchronously reading a text file and displaying its contents in a TextBox
in a Windows Forms application.
VIDEO TUTORIAL
- How to Print Text in a Windows Form Application Using C#
- How to fill ComboBox and DataGridView automatically in C#
- How to Read text file and Sort list in C#
- How to pass ListView row data into another Form in C#
- How to read and write to text file in C#
- How to make a Countdown Timer in C#
- How to Display selected Row from DataGridView to TextBox in C#
- How to Get all Forms and Open Form with Form Name in C#