C# Files

In C#, there is a Files class from the  bSystem.IO namespace which enables us to work with files. Files class can be used by adding the namespace,

using System.IO;

Files.MethodName();

Some methods of Files class are,

1. AppendText() – This method appends text at the end of an existing file.

2. Copy() –  This method copies a file.

3. Create() – This method creates a file or overwrites an existing file.

4. Delete() – This method Deletes a file.

5. Replace() – This method replaces the content of a file with the content of another file.

6. ReadAllText() – Reads the contents of the file.

7. WriteAllText() – Creates a file and writes content in it, if the file already exists it overwrites it.

8. Exists() – This method checks whether the file exists or not.

using System.IO;  

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.