write text in text file c# code example

Example 1: c# create a text file

//File and path you want to create and write to
string fileName = @"C:\Temp\Temp.txt"; 
//Check if the file exists
if (!File.Exists(fileName)) 
{
    // Create the file and use streamWriter to write text to it.
	//If the file existence is not check, this will overwrite said file.
	//Use the using block so the file can close and vairable disposed correctly
    using (StreamWriter writer = File.CreateText(fileName)) 
    {
        writer.WriteLine("Hello World");
    }	
}

Example 2: 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 3: 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();  
  
        }  
    }  
}