c# save string to file 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: asp.net c# write string to text file

using (StreamWriter writer = new StreamWriter("email.txt", true)) //// true to append data to the file
{
    writer.WriteLine("your_data"); 
}

Example 3: List string to file C#

string[] lines = { "First line", "Second line", "Third line" };
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
lines = { "Fourth line", "Fith line" };
System.IO.File.AppendAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);