Jim
Jim

Reputation: 183

How to use StreamReader in C# (newbie)

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.

Upvotes: 8

Views: 34842

Answers (8)

Kent Boogaart
Kent Boogaart

Reputation: 178660

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);

Upvotes: 18

DCNYAM
DCNYAM

Reputation: 12126

You need to add a reference to the System.IO assembly. You can do this via the "My Project" properties page under the References tab.

Upvotes: 0

Quibblesome
Quibblesome

Reputation: 25409

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.

Upvotes: 9

Eric W
Eric W

Reputation: 570

StreamReader is defined in System.IO. You either need to add

using System.IO;

to the file or change your code to:

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

Upvotes: 2

CheGueVerra
CheGueVerra

Reputation: 7963

Make sure you have the System assembly in your reference of the project and add this to the using part:

using System.IO;

Upvotes: 3

Gene
Gene

Reputation: 210

Make sure you are have "using System.IO;" at the top of your module. Also, you don't need the extra parenthesis at the end of "new StreamReader(FileDialog.filename)".

Upvotes: 2

Werg38
Werg38

Reputation: 1130

Make sure you include using System.IO in the usings declaration

Upvotes: 2

Steven A. Lowe
Steven A. Lowe

Reputation: 61233

try

using System.IO;


StreamReader arrComputer = new StreamReader(FileDialog.filename);

Upvotes: 4

Related Questions