string StreamReader 的行到字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12633815/
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-09-09 01:37:09  来源:igfitidea点击:

Lines of a StreamReader to an array of string

stringc#-4.0streamreader

提问by whoone

I want to get a string[]assigned with a StreamReader. Like:

我想获得一个string[]带有StreamReader. 喜欢:

try{
    StreamReader sr = new StreamReader("a.txt");
    do{
        str[i] = sr.ReadLine();
        i++;
    }while(i < 78);
}
catch (Exception ex){
    MessageBox.Show(ex.ToString());
}

I can do it but can't use the string[]. I want to do this:

我可以做到,但不能使用字符串[]。我想做这个:

MessageBox.Show(str[4]);

If you need further information feel free to ask, I will update. thanks in advance...

如果您需要更多信息,请随时询问,我会更新。提前致谢...

回答by C???

If you really want a string array, I would approach this slightly differently. Assuming you have no idea how many lines are going to be in your file (I'm ignoring your hard-coded value of 78 lines), you can't create a string[]of the correct size up front.

如果你真的想要一个字符串数组,我会稍微不同地处理这个。假设您不知道文件中有多少行(我忽略了 78 行的硬编码值),您无法预先创建string[]正确大小的 。

Instead, you could start with a collection of strings:

相反,您可以从一组字符串开始:

var list = new List<string>();

Change your loop to:

将您的循环更改为:

using (var sr = new StreamReader("a.txt"))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        list.Add(line);
    }
}

And then ask for a string array from your list:

然后从您的列表中请求一个字符串数组:

string[] result = list.ToArray();

Update

更新

Inspired by Cuong's answer, you can definitely shorten this up. I had forgotten about this gem on the Fileclass:

Cuong 回答的启发,您绝对可以缩短此时间。我已经忘记了File课堂上的这颗宝石:

string[] result = File.ReadAllLines("a.txt");

What File.ReadAllLinesdoes under the hood is actually identical to the code I provided above, except Microsoft uses an ArrayListinstead of a List<string>, and at the end they return a string[]array via return (string[]) list.ToArray(typeof(string));.

什么File.ReadAllLines引擎盖下做实际上是相同的我上面提供的码,除了Microsoft使用的ArrayList,而不是一个List<string>,并且在结束时,他们返回一个string[]通孔阵列return (string[]) list.ToArray(typeof(string));