Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use StreamReader in C# (newbie)

Tags:

c#

.net

stream

I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following:

StreamReader arrComputer = new StreamReader(FileDialog.filename)();

I got this exception:

The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?)  

I'm very new to C# so I'm sure I'm making a newbie mistake.

like image 992
Jim Avatar asked Nov 10 '08 20:11

Jim


2 Answers

You need to import the System.IO namespace. Put this at the top of your .cs file:

using System.IO;

Either that, or explicitly qualify the type name:

System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename);
like image 159
Kent Boogaart Avatar answered Oct 05 '22 23:10

Kent Boogaart


You'll need:

using System.IO;

At the top of the .cs file. If you're reading text content I recommend you use a TextReader which is bizarrely a base class of StreamReader.

try:

using(TextReader reader = new StreamReader(/* your args */))
{
}

The using block just makes sure it's disposed of properly.

like image 36
Quibblesome Avatar answered Oct 05 '22 23:10

Quibblesome