c# save text in file code example

Example 1: write text files with C#

// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);

...

// Open the file to read from.
string readText = File.ReadAllText(path);

Example 2: save text input into a txt file in c#

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Linq;  
using System.Text;  
using System.Windows.Forms;  
using System.IO;  
  
namespace WindowsFormsApplication2  
{  
    public partial class Form1: Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            TextWriter txt = new StreamWriter("C:\\demo\\demo.txt");  
            txt.Write(textBox1.Text);  
            txt.Close();  
  
        }  
    }  
}