Utilizor
Contact Us

C# Files

Read from and write to files using System.IO.

C# Files

The File class from the System.IO namespace allows us to work with files:

using System.IO;  // include the System.IO namespace

The File class has many useful methods for creating and getting information about files. For example:

  • AppendAllText() - Appends text to the end of an existing file.
  • Copy() - Copies a file.
  • Create() - Creates or overwrites a file.
  • Delete() - Deletes a file.
  • Exists() - Tests whether the file exists.
  • ReadAllText() - Reads the contents of a file.
  • Replace() - Replaces the contents of a specified file with the contents of another file.
  • WriteAllText() - Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

Examples

Write and Read File

Writing to a file and reading from it.

using System;
using System.IO;  // include the System.IO namespace

class Program
{
  static void Main(string[] args)
  {
    string writeText = "Hello World!";  // Create a text string
    File.WriteAllText("filename.txt", writeText);  // Create a file and write the content of writeText to it

    string readText = File.ReadAllText("filename.txt");  // Read the contents of the file
    Console.WriteLine(readText);  // Output the content
  }
}