Save Data To Text File In Windows Form Using C#

We write some data in textbox and it will be save in a text file in the given path.

Initial chamber

Step 1: Open Visual Studio 2010, Go to File, New, Projects, then under Visual C# select Windows.

Windows form application

You can change the name of the project and browse your project to different location too. And then press – OK.

Now go to any drive, make a folder demo and save a demo.txt file.

demo

Design chamber

Step 2: Now open your Form1.cs file, where we create our design for inserting data into Text File. We will drag one Textbox and a button to Form1.cs. You will see your Form look like this.

Form1.cs [design]:

design

Change the property of textbox -  Multiline as True.

Multiline

Code chamber


Right click on the blank part of Form1.cs and View Code. You will see you are entered in the code part of the form. Write the following code and then Press F5 to run the project.

Form1.cs:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO;  
  10.   
  11. namespace WindowsFormsApplication2  
  12. {  
  13.     public partial class Form1: Form  
  14.     {  
  15.         public Form1()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.   
  20.         private void button1_Click(object sender, EventArgs e)  
  21.         {  
  22.             TextWriter txt = new StreamWriter("C:\\demo\\demo.txt");  
  23.             txt.Write(textBox1.Text);  
  24.             txt.Close();  
  25.   
  26.         }  
  27.     }  
  28. }  
Output chamber

Output

Save to text file

Save to text File

 


Similar Articles