The .NET Framework provides a namespace System.IO which contains all functions you need to read and write files. Reading and writing files can be achieved in a variety of ways, but the simplest approach, is to use the File class.using System; using System.IO; public c...
The File class defines a number of methods that make reading and writing files easy.
Writing a text file
To write a text file, you can use the File.WriteAllText method. This method has two overloads, the first accepting a path and the contents (as a string), and the next also accepts an encoding.
public static void WriteAllText(string path, string contents); public static void WriteAllText(string path, string contents, Encoding encoding);
We'll cover encodings later in a future tutorial, so for now, let's stick with the first method:
File.WriteAllText(@".\hello.txt", "Hello World");
Using that method call, we're writing the string "Hello World", to a local file named "hello.txt". Using the ".\" prefix in the path indicates that we are using the current directory - this is normally the directory from which your program is executing.
We're using a form of a string constant known as a verbatim string. Any constant string that starts with the "@" prefix before the leading quotation. Using a verbatim string changes the semantics of escape characters:
@"There is not a new line at the end of this string\n";
This is useful when writing out path variables as the "\" character represents a path separator on Windows machines. You can also use a regular constant string, but you need to escape the path separator, resulting in a double "\":
If the file indicated by the path variable does not exist, it is created. If it does exist, then it is overwritten.
You'll see later in this tutorial how you can achieve finer control over these operations.
Reading a text file
Reading a text file is also a simple operation. The File.ReadAllText method also has two overloads:
public static string ReadAllText(string path); public static string ReadAllText(string path, Encoding encoding);
The result of the method can be assigned to a variable.
string contents = File.ReadAllText(@".\hello.txt");
If the file does not exist, then a FileNotFoundException is thrown to inform you of this fact.
Deleting a text file
You can delete a text file using the File.Delete method. This accepts the path to the file you want to delete.
public static void Delete(string path);
The method does not return anything (it is void), so you can simply call it: