7.2. StreamWriter
The FileStream
class provides a stream
of bytes[] of data for file operations, supporting both synchronous
and asynchronous read and write operations. To use the FileStream class in C#, first of all,
you need to include the System.IO namespace
and then you need to create an
instance
of the FileStream class in order to use its functionalities to, for example,
create a new file or to open an existing file.
For handling files, the StreamWriter
class is more popular in writing files
and it is very helpful in writing text data into a file. It is easy to use and provides
a complete set of constructors [1] and methods to work on it. Specifically,
the StreamWriter
class in C# is used for writing characters to stream in a particular format.
7.2.1. Writing Files
Observe the following program (first_file.cs
):
1 using System;
2 using System.IO;
3
4 namespace IntroCSCS
5 {
6 class Ch07File // basics of file writing
7 {
8 public static void Main()
9 {
10 StreamWriter writer = new StreamWriter("sample.txt");
11 writer.WriteLine("This program is writing");
12 writer.WriteLine("our first file.");
13 writer.Close();
14 }
15 }
16 }
Look at the code:
- The
System.IO
namespace: Namespace: Note the
using System.IO
namespace being used at the top. It gives the program access to the functionalities in the System.IO namespace. For your current concern, this means a number of classes that contains many methods that you use.You will always need to be using
System.IO
when working with files. Here is a slightly different use of a dot,.
, to indicate a subsidiary namespace. Under System.IO, there are plenty of classes (with methods defined inside) for system IO operations, such as: - File, - StreamWriter, - FileStream, - StreamReader, - Directory, - Path, etc.
- The
- The StreamWriter Class:
variable: The first line of the body of
Main
creates aStreamWriter
object assigned to the variablewriter
.A
StreamWriter
links C# to your computer’s file system for writing, not reading.Files are objects, like a Random, and you use the
new
syntax to create a new one.The StreamWriter class parameter (“constructor”, to be covered in later chapters) gives the name of the file to connect to the program,
sample.txt
, which is the same as the file name we saw created by the program.
Warning
If the file already existed, the old contents are destroyed silently by creating a
StreamWriter
.
writer.WriteLine(): The writer variable is of data type (or just type) StreamWriter and StreamWriter has method WriteLine() just like the Console class. The difference is that Console.WriteLine writes to the console/terminal, whereas StreamWriter.WriteLine writes out a data stream to a file followed by a newline character.
Note
Just as you can use a Composite formatting with functions
Write
andWriteLine
of theConsole
class, you can also use a format string with the corresponding methods of aStreamWriter
, and embed fields by using braces in the format string.writer.Close(): The Close() method closes the current StreamWriter object and the underlying stream. The Close() method is important for cleaning up. Until this line, this C# program controls the file, and nothing may be actually written to the operating system file yet: Since initiating a file operation is thousands of times slower than memory operations, C# buffers data, saving small amounts and writing a larger chunk all at once.
Warning
The call to the
Close
method is essential for C# to make sure everything is really written, and to relinquish control of the file for use by other programs. It is a common bug to write a program where you have the code to add all the data you want to a file, but the program does not end up creating a file. Usually this means you forgot to close the file!
7.2.1.1. Directory path
If you do not use any operating system directory separators in the name
('\'
or '/'
, depending on your operating system), then the file will lie in the
current directory. For example, you may create a data
directory under your
introcscs directory and place all data files in it.
Footnotes