Professional Documents
Culture Documents
Csharp File Handling
Csharp File Handling
File Handling
File Handling in C#
In C# there are various ways to handle files. In this note, code snippets of the basic
functions required for file handling and examples of how to handle text files and serialisable
files are given. Note that in practice, all file handling code should be surrounded with
exception handling code so that if something fails, the program would not crash.
Copying a file
File.Copy("MyFile.txt","MyFile2.txt",true);
Note the third argument in the above Copy method is used to indicate whether the [second]
file should be overwritten or not if it already exists.
Delete a file
File.Delete("MyFile2.txt");
Moving a file
File.Move("MyFile.txt","MySubDir\\MyMovedFile.txt");
CIS2052
Advanced Programming I [C# Programming Language]
File Handling
Text files
Writing text to a text file
StreamWriter myFile = File.CreateText("MyFile.txt");
myFile.WriteLine("This text will be stored in a text file");
myFile.Close();
Serialisation
Serialisation is the process of converting an object into a stream of bytes in order to store
the object or transmit it to memory, a database, or a file. Its main purpose is to save the
state of an object in order to be able to recreate it when needed. The reverse process is
called deserialisation.
Note that in two following two examples, the class Person is used.
CIS2052
Advanced Programming I [C# Programming Language]
File Handling