.. index:: file (StreamWriter); write and close double: StreamWriter; WriteLine class; StreamWriter close file .. _filewrite: ``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 [#constructor]_ and methods to work on it. Specifically, the ``StreamWriter`` class in C# is used for writing characters to stream in a particular format. Writing Files --------------- Observe the following program (``first_file.cs``): .. code-block:: csharp :linenos: :emphasize-lines: 10-12 using System; using System.IO; namespace IntroCSCS { class Ch07File // basics of file writing { public static void Main() { StreamWriter writer = new StreamWriter("sample.txt"); writer.WriteLine("This program is writing"); writer.WriteLine("our first file."); writer.Close(); } } } 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 StreamWriter Class: - variable: The first line of the body of ``Main`` creates a ``StreamWriter`` object assigned to the variable ``writer``. - 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. .. index:: StreamWriter; format string StreamWriter; Write .. note:: Just as you can use a :ref:`Format-Strings` with functions ``Write`` and ``WriteLine`` of the ``Console`` class, you can also use a format string with the corresponding methods of a ``StreamWriter``, 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! 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. .. rubric:: Footnotes .. [#constructor] The concept and use of constructor will be covered in subsequent chapters regarding object-oriented programming.