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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/279114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:20:08  来源:igfitidea点击:

How to use StreamReader in C# (newbie)

c#.netstream

提问by Jim

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

采纳答案by Kent Boogaart

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

您需要导入System.IO命名空间。将其放在 .cs 文件的顶部:

using System.IO;

Either that, or explicitly qualify the type name:

要么,要么明确限定类型名称:

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

回答by Steven A. Lowe

try

尝试

using System.IO;


StreamReader arrComputer = new StreamReader(FileDialog.filename);

回答by Werg38

Make sure you include using System.IOin the usings declaration

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

回答by Gene

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

确保你有“使用 System.IO;” 在模块的顶部。此外,您不需要“new StreamReader(FileDialog.filename)”末尾的额外括号。

回答by CheGueVerra

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

确保您在项目的参考中有系统程序集并将其添加到使用部分:

using System.IO;

回答by Eric W

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

StreamReader 在 System.IO 中定义。你要么需要添加

using System.IO;

using System.IO;

to the file or change your code to:

到文件或将您的代码更改为:

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

回答by Quibblesome

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.

在 .cs 文件的顶部。如果您正在阅读文本内容,我建议您使用 TextReader,它奇怪地是 StreamReader 的基类。

try:

尝试:

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

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

using 块只是确保它被正确处理。

回答by DCNYAM

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.

您需要添加对 System.IO 程序集的引用。您可以通过“参考”选项卡下的“我的项目”属性页面执行此操作。