简体   繁体   中英

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.

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

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.

try

using System.IO;


StreamReader arrComputer = new StreamReader(FileDialog.filename);

确保在项目的引用中有系统程序集,并将其添加到using部分:

using System.IO;

确保在usings声明中包含using System.IO

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)".

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM