【问题标题】:Lines of a StreamReader to an array of stringStreamReader 的行到字符串数组
【发布时间】:2012-09-28 04:58:19
【问题描述】:

我想获得一个分配有StreamReaderstring[]。喜欢:

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

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

MessageBox.Show(str[4]);

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

【问题讨论】:

    标签: string c#-4.0 streamreader


    【解决方案1】:

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

    相反,您可以从字符串集合开始:

    var list = new List<string>();
    

    将循环更改为:

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

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

    string[] result = list.ToArray();
    

    更新

    Cuong's answer 的启发,您绝对可以将其缩短。我忘记了 File 课程上的这颗宝石:

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

    File.ReadAllLines 在后台所做的实际上与我上面提供的代码相同,除了 Microsoft 使用 ArrayList 而不是 List&lt;string&gt;,最后它们通过 return (string[]) list.ToArray(typeof(string)); 返回一个 string[] 数组.

    【讨论】:

    • 正是我需要的。谢谢老兄:D
    • @whoone:查看我的更新答案。有一个不错的快捷方式可以为您节省几行代码。
    • 我在添加引用中找不到 System.IO.File。你有解决办法吗?
    • File 是 CLR 的一部分。你只需要导入System.IO
    • ReadAllLines 抛出一个错误,指出该文件正在为我使用。对于我的解决方案,我不得不重新使用带有 File.Open 的流式阅读器。任何人都知道如何使用 File.Open 和 File.ReadAllLines 中的“FileMode.Open、FileAccess.ReadWrite、FileShare.ReadWrite”参数?
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    相关资源
    最近更新 更多