1.5. Opening a Text File for Reading and Writing

Let's assume that the user has entered a valid text file name for the program. Our job, then, is to open the file, read its contents, and after processing those contents, write the results out to a second file, which we need to create. Let's see how we do this.

Support for file input/output is encapsulated in the System.IO namespace. So the first thing we need to do is open the namespace to the compiler:

using System.IO;

Text files are read and written through the StreamReader and StreamWriter classes. There are various ways to create instances of these classes—for example,

 string file_name = @"C:\fictions\gnome.txt"; StreamReader freader = File.OpenText( file_name ); StreamWriter fwriter = ...

Get C# Primer: A Practical Approach now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.