0
0
C Sharp (C#)programming~5 mins

Why file operations matter in C Sharp (C#)

Choose your learning style9 modes available
Introduction

File operations let your program save and read information on your computer. This helps keep data safe even after the program stops.

Saving user settings so they stay the same next time the program runs.
Storing game scores or progress to continue later.
Reading a list of names or data from a file to use in the program.
Logging errors or actions to check what happened after running.
Sharing data between different programs by writing and reading files.
Syntax
C Sharp (C#)
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.

Examples
This saves the sentence into a file named notes.txt.
C Sharp (C#)
File.WriteAllText("notes.txt", "Remember to buy milk.");
This reads the text from notes.txt and prints it on the screen.
C Sharp (C#)
string notes = File.ReadAllText("notes.txt");
Console.WriteLine(notes);
Sample Program

This program saves a greeting message to a file and then reads it back to show on the screen.

C Sharp (C#)
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);
    }
}
OutputSuccess
Important Notes

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.

Summary

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.