FILE I/O Operations

advertisement
FILE I/O Operations
Writing 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:
Writing 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.
Writing 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
Exercise

Write a program that inserts the lines that are
taken from console to a file. Program will stop
if user enters “:wq!“
Formatting 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.
Formatted 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.
Exercise




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, namesurname: 40 characters.
Program will terminate after taking 5 student entry.
Reading 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.
Reading from file
Does file
exist?
Open file for
reading and
create reader
object.
Read one line
per iteration
until end of file
Print the line
that is read
to the output
Exercise



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.
Serialization


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.
Serialization

[Serializable]

Marks whether class is serializable or not.
Serialization - Serialize
Serialization - Deserialize
Download