C# Write File
Learn how to write and save files in C#
āļø Writing Files in C#
C# makes file writing straightforward with the File class. You can create new files, write text content, append data, and save information permanently to disk using simple, intuitive methods.
// Simple file writing
using System.IO;
File.WriteAllText("output.txt", "Hello, World!");
Console.WriteLine("File created successfully!");
Output:
File created successfully!
Understanding File Writing in C#
Writing files allows you to save data permanently. C# provides several methods: writing all content at once, appending to existing files, or writing line by line. You can create logs, save user data, export reports, and store configuration settings efficiently using these file operations.
WriteAllText
Write string to file
File.WriteAllText("file.txt",
"Content here");
WriteAllLines
Write array of lines
string[] lines = {"Line 1", "Line 2"};
File.WriteAllLines("file.txt", lines);
AppendAllText
Add to existing file
File.AppendAllText("file.txt",
"New content");
StreamWriter
Write with more control
using StreamWriter sw =
new StreamWriter("file.txt");
sw.WriteLine("Text");
š¹ Write Text to File
Writing text to a new file in C# creates or overwrites a file with specified content. The simplest method is File.WriteAllText(path, content). For more control, use StreamWriter with options for appending or encoding. Ensure you have write permissions to the target directory. This basic operation is foundational for logging, data export, or file generation tasks.
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
string filePath = "message.txt";
string content = "Hello from C#!\nThis is a new file.";
// Write content to file (creates or overwrites)
File.WriteAllText(filePath, content);
Console.WriteLine($"File '{filePath}' created successfully!");
Console.WriteLine($"Content written: {content.Length} characters");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output:
File 'message.txt' created successfully! Content written: 35 characters
š¹ Write Multiple Lines
Writing multiple lines to a file in C# efficiently handles arrays or lists of strings as separate lines. Use File.WriteAllLines(path, stringArray) to write each element on a new line. Alternatively, StreamWriter with a loop offers customization. This is perfect for saving lists, logs, or any data where line separation is meaningful.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "list.txt";
// Create array of lines
string[] lines = {
"Item 1: Apple",
"Item 2: Banana",
"Item 3: Orange",
"Item 4: Grape",
"Item 5: Mango"
};
try
{
// Write all lines to file
File.WriteAllLines(filePath, lines);
Console.WriteLine($"Successfully wrote {lines.Length} lines");
Console.WriteLine($"File saved as: {filePath}");
}
catch (IOException ex)
{
Console.WriteLine($"Error writing file: {ex.Message}");
}
}
}
Output:
Successfully wrote 5 lines File saved as: list.txt
š¹ Append to Existing File
Appending text to an existing file in C# adds content to the end without overwriting. Use File.AppendAllText(path, content) for simple additions or File.AppendAllLines for multiple lines. With StreamWriter, pass true as the append parameter. This is essential for logging, audit trails, or progressively building a file.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "log.txt";
try
{
// Create initial content
File.WriteAllText(filePath, "Log started\n");
Console.WriteLine("Log file created");
// Append new entries
File.AppendAllText(filePath, "Entry 1: User logged in\n");
File.AppendAllText(filePath, "Entry 2: Data processed\n");
File.AppendAllText(filePath, "Entry 3: User logged out\n");
Console.WriteLine("Log entries added");
// Read and display the complete log
string logContent = File.ReadAllText(filePath);
Console.WriteLine("\nComplete Log:");
Console.WriteLine(logContent);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output:
Log file created Log entries added Complete Log: Log started Entry 1: User logged in Entry 2: Data processed Entry 3: User logged out
š¹ Using StreamWriter
StreamWriter in C# offers advanced control for writing text files, including encoding, buffering, and asynchronous writes. Create it with a path and optional append/encoding settings. Methods like WriteLine() and Write() provide flexibility. Always use using or call Dispose() to flush buffers and close the file, ensuring data integrity.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "report.txt";
try
{
// Using statement ensures proper disposal
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("=== Sales Report ===");
writer.WriteLine($"Date: {DateTime.Now:yyyy-MM-dd}");
writer.WriteLine();
writer.WriteLine("Product Sales:");
writer.WriteLine("- Laptop: $1200");
writer.WriteLine("- Mouse: $25");
writer.WriteLine("- Keyboard: $75");
writer.WriteLine();
writer.WriteLine("Total: $1300");
}
Console.WriteLine("Report generated successfully!");
}
catch (IOException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output:
Report generated successfully!
š¹ Write User Input to File
Saving user-entered data to a file in C# involves capturing input and persisting it. Gather input via Console.ReadLine() or UI controls, validate it, then write using File.WriteAllText or StreamWriter. Consider file format (plain text, CSV, JSON) based on the data structure. Implement confirmation messages and error handling for a user-friendly experience.
using System;
using System.IO;
class Program
{
static void Main()
{
Console.WriteLine("=== Note Taking App ===");
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your note: ");
string note = Console.ReadLine();
string filePath = "notes.txt";
try
{
// Create note with timestamp
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string entry = $"[{timestamp}] {name}: {note}\n";
// Append to notes file
File.AppendAllText(filePath, entry);
Console.WriteLine("\nā Note saved successfully!");
Console.WriteLine($"Saved to: {filePath}");
}
catch (Exception ex)
{
Console.WriteLine($"Error saving note: {ex.Message}");
}
}
}
Output:
=== Note Taking App === Enter your name: John Enter your note: Remember to buy groceries ā Note saved successfully! Saved to: notes.txt
š¹ Write CSV File
Creating a CSV file in C# structures data into comma-separated values, readable by spreadsheets and databases. Manually format strings with commas and line breaks, or use libraries like CsvHelper for complex scenarios. Ensure proper handling of commas and quotes within data. CSV files are ideal for exporting tabular data for external analysis or import.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "employees.csv";
try
{
// Create CSV header
string[] csvLines = {
"ID,Name,Department,Salary",
"1,John Doe,IT,75000",
"2,Jane Smith,HR,65000",
"3,Bob Johnson,Sales,70000",
"4,Alice Brown,IT,80000"
};
// Write CSV file
File.WriteAllLines(filePath, csvLines);
Console.WriteLine("CSV file created successfully!");
Console.WriteLine($"File: {filePath}");
Console.WriteLine($"Records: {csvLines.Length - 1}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output:
CSV file created successfully! File: employees.csv Records: 4