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 |
---|---|
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. 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. |
static void Main(string[] args) { string msg = "Hello world from C#"; File.WriteAllText("C:/tmp/csharp-file.txt", msg); } | 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 The WriteAllText() method writes a sequence of ASCII charaters to text file. |
0 Comments