Windows Forms: How to read and write to text file in C#
By FoxLearn 7/4/2017 9:59:50 PM 10.39K
How to read and write to text (*.txt) file in c#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "TextFile" and then click OK
Step 2: Design your form as below
Step 3: Add code to button click event handler as below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TextFile { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private async void btnRead_Click(object sender, EventArgs e) { //Read text file using(OpenFileDialog ofd = new OpenFileDialog() { Filter="Text Documents|*.txt", ValidateNames = true, Multiselect = false }) { if (ofd.ShowDialog() == DialogResult.OK) { using(StreamReader sr = new StreamReader(ofd.FileName)) { txtText.Text = await sr.ReadToEndAsync(); } } } } private async void btnWrite_Click(object sender, EventArgs e) { //Write text file using(SaveFileDialog sfd = new SaveFileDialog() { Filter="Text Documents|*.txt", ValidateNames = true }) { if (sfd.ShowDialog() == DialogResult.OK) { using(StreamWriter sw = new StreamWriter(sfd.FileName)) { await sw.WriteLineAsync(txtText.Text); MessageBox.Show("You have been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } } }
VIDEO TUTORIALS
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#
Categories
Popular Posts
How to Download Chromedriver for Selenium
08/29/2024
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What is ARM architecture?
04/01/2024