Windows Forms: How to read and write to text file in C#
By FoxLearn 7/4/2017 9:59:50 PM 10.5K
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 read an image file in C#
- How to use BackgroundWorker in C#
- How to protect .NET code from reverse engineering
- How to Get value from another Form in C#
- How to make a Notepad in C#
- How to Receive SMS from WhatsApp in C#
- How to Add Combobox to DataGridView in C#
- How to Create Multiple pages on the Form using Panel control in C#
Categories
Popular Posts
Simple Responsive Login Page
11/11/2024
Free Responsive HTML5 & CSS3 Login Page
11/11/2024
tsParticles Authentication Template
11/11/2024
Bootstrap 4 Login Page Template
11/11/2024
HTML Template Animated Login Form
11/11/2024