Introduction
File operations let your program save and read information on your computer. This helps keep data safe even after the program stops.
Jump into concepts and practice - no test required
File operations let your program save and read information on your computer. This helps keep data safe even after the program stops.
using System.IO; // To write text to a file File.WriteAllText("filename.txt", "Hello World"); // To read text from a file string content = File.ReadAllText("filename.txt");
Use File.WriteAllText to save text to a file quickly.
Use File.ReadAllText to get all text from a file at once.
notes.txt.File.WriteAllText("notes.txt", "Remember to buy milk.");
notes.txt and prints it on the screen.string notes = File.ReadAllText("notes.txt");
Console.WriteLine(notes);This program saves a greeting message to a file and then reads it back to show on the screen.
using System; using System.IO; class Program { static void Main() { string fileName = "greeting.txt"; string message = "Hello, friend!"; // Save message to file File.WriteAllText(fileName, message); // Read message from file string readMessage = File.ReadAllText(fileName); Console.WriteLine("Message saved and read from file:"); Console.WriteLine(readMessage); } }
File paths can be simple names or full paths like C:\Users\Name\file.txt.
Always handle exceptions in real programs to avoid crashes if files are missing or locked.
File operations let programs save and load data on your computer.
This helps keep information even after the program stops running.
Common uses include saving settings, logs, and sharing data.
using System;
using System.IO;
class Program {
static void Main() {
File.WriteAllText("test.txt", "Hello World");
string content = File.ReadAllText("test.txt");
Console.WriteLine(content);
}
}string content = File.ReadAllText("missing.txt");
Console.WriteLine(content);