C# tutorial-File Stream: Sequential-Access File
File Stream in C#
So far we haven’t talked about writing words or sentences to a hard drive or reading from it. This part will guide you through those processes. File streams can be stored in plain text and binary format. There are two types of file streams—sequential-access file and random-access file.
In the below example, to write text to a file sequentially, we need two objects--FileStream fs object and StreadWriter fw object. The StreamWriter fw object takes the FileStream object fs as its argument.
The first argument of the FileStream constructor is the file name and its path that you want to create, write to, to read from. The second argument is the file mode. There are four main file modes that you should know. These file modes are shown blow:
-Append appends the text to the end of a file if the file already exists. If the file doesn't exist it will be created. This file mode is used in conjunction with the write file access.
-Create creates a new file if it doesn't exist. If it exists it will be overridden.
-CreateNew creates a new file if it doesn't exist. An error will occur is the file already exists.
-OpenOrCreate opens a file if it already exists or create a new one if it doesn't exist.
The third argument of the FileStream constructor is file access. There are three main types of file access you should know:
-Read can only read data from a file.
-ReadWrite can read and write data to a file.
-Write can only write data to a file
Reading from a sequential-access file
To read data from a file you need one FileStream object and one StreamReader object. The StreamReader object accepts the FileStream object as its argument.