Files

An important asect of any programming language is its ability to perform IO operation, especially file IO operations. The System.IO.File class ca be used to peform a number of file IO operations.

The File class cannot be instantiated in the same way as other classes are normally instantiated. You use its methods by prefixing all of its methods, fields, and properties with File.

Example

Result

Example

Result

static void Main( string[] args ) { Console.WriteLine(File.ReadAllText("C:\\tmp\\Ogre.log")); }

 

static void Main( string[] args ) { Console.WriteLine(File.ReadAllText(@"C:\tmp\Ogre.log")); }

 

static void Main( string[] args ) { Console.WriteLine(File.ReadAllText("C:/tmp/Ogre.log")); }

The simplest File program you could write is shown here.

Notice the use of double \\ character. This is so that the oblique (back slash) character is treated as the literal character and not an escape character.

This simple program will read all the ASCII characters from the given text file and display them on the screen.

Alternatively you can use the @ character before the string literal to ensure that each character in the string is treated as a literal value and not translated

 

 

If you want to make your code portable across multiple platforms (Windows and Linux/Unix) avoid using the oblique character and replace it with a forward slash as shown here.

In this example ReadLines() reads all the lines (each line is delimited by a CR/LF sequence) into a collection that can be used as

 

 

This simple application will write the ASCII characters to a file called “C:/tmp/csharp-file.txt”

After running this snippet of code, open the file csharp-file.txt, and its contents should read as "Hello world from C#"

The WriteAllText() method writes a sequence of ASCII characters to text file.