Title: FILE I/O Operations
1FILE I/O Operations
2Writing to a file
- In C language System.IO namespace is used for
file operations. - We should use StreamWriter class especially when
Turkish support is needed. - Turkish language support is provided by Encoding
class in System.Text namespace.
Needed namespaces
3Writing to a file
- StreamWriter Used for writing to a file.
- Encoding Used for determining character code
page of the file. - StreamWriter.WriteLine(string) Writes a line to
the file.
4Writing to a file
File name and path
Object that will write to the file
Crates file with Turkish support
Write a line to the file
5Exercise
- Write a program that inserts the lines that are
taken from console to a file. Program will stop
if user enters wq!
6Formatting Strings
- string.Format used for formatting strings with a
given format. - We could be asked for writing our files in a row
and column basis. We could use string.Format
function at these situations.
7Formatted Writing
In the example above, lines are written to the
file with right alignment. Because we used
string.Format function before writing to the
console. First parameter of the function tells
to reserve 20 characters of space to the second
parameter.
8Exercise
- Write a program that writes formatted data to a
file which are taken from user. - Program will first ask for student number then
name and surname. - Program will write these data to a file with
reserved spaces for student number 15
characters, name-surname 40 characters. - Program will terminate after taking 5 student
entry.
9Reading from file
- StreamReader Used for reading from a file.
- string StreamReader.ReadLine() Used from
reading a line from a file. - It is a good practice to check the existence of
the file with File.Exists(string path) method
before accessing the file.
10Reading from file
Open file for reading and create reader object.
Does file exist?
Read one line per iteration until end of file
Print the line that is read to the output
11Exercise
- Write a program that reads the student
information from file which is created in the
previous example. - Program will read the file line by line and write
each line to a new file. Each file will be named
with the student name which it contains. - In other words, after program is executed there
will be 5 files for 5 students.
12Serialization
- It is used for storing and reading objects
to/from a file which are not string types. - We use FileStream and BinaryFormatter classes.
- System.IO. FileStream
- System.Runtime.Serialization.Formatters.Binary.
BinaryFormatter - Serialize and Deserialize functions are used for
saving and loading.
13Serialization
- Serializable
- Marks whether class is serializable or not.
14Serialization - Serialize
15Serialization - Deserialize