简体   繁体   English

如何在C#中使用StreamReader(新手)

[英]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: 我正在尝试读取文本文件的内容,在这种情况下是一个计算机名称列表(Computer1,computer2等),我认为StreamReader将是您将使用的,但是当我执行以下操作时:

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. 我对C#很新,所以我确定我犯了一个新手的错误。

You need to import the System.IO namespace. 您需要导入System.IO命名空间。 Put this at the top of your .cs file: 把它放在.cs文件的顶部:

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. 在.cs文件的顶部。 If you're reading text content I recommend you use a TextReader which is bizarrely a base class of StreamReader. 如果您正在阅读文本内容,我建议您使用TextReader,这是一个奇怪的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;" 确保你“使用System.IO;” at the top of your module. 在您的模块的顶部。 Also, you don't need the extra parenthesis at the end of "new StreamReader(FileDialog.filename)". 此外,您不需要“new StreamReader(FileDialog.filename)”末尾的额外括号。

StreamReader is defined in System.IO. StreamReader在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. 您需要添加对System.IO程序集的引用。 You can do this via the "My Project" properties page under the References tab. 您可以通过“参考”选项卡下的“我的项目”属性页面执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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