O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.4. Reading from and writing to text files

You can use the StreamReader class for reading, and StreamWriter for writing. Unlike the more generalized FileStream class, StreamReader and StreamWriter are specialized classes for text files containing ASCII or Unicode characters. There are useful methods which make text file access more convenient.

18.4.1. Reading using StreamReader

StreamReader has several overloaded constructors but here are the two most useful ones:

  • public StreamReader (string path)

  • public StreamReader (string path, Encoding encoding)

If the first constructor is used, StreamReader will try to determine the file's encoding format from the text file itself. [7]

[7] It is possible to determine if a text file is encoded using Unicode ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required