C# how to convert File.ReadLines into string array?

前端 未结 3 1698
野趣味
野趣味 2020-12-05 17:59

The question that I have is regarding converting the process of reading lines from a text file into an array instead of just reading it.

The error in my codes appear

相关标签:
3条回答
  • 2020-12-05 18:26

    File.ReadLines() returns an object of type System.Collections.Generic.IEnumerable<String>
    File.ReadAllLines() returns an array of strings.

    If you want to use an array of strings you need to call the correct function.

    You could use Jim solution, just use ReadAllLines() or you could change your return type.

    This would also work:

    System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
    

    You can use any generic collection which implements IEnumerable. IList for an example.

    0 讨论(0)
  • 2020-12-05 18:27
    string[] lines = File.ReadLines("c:\\file.txt").ToArray();
    

    Although one wonders why you'll want to do that when ReadAllLines works just fine.

    Or perhaps you just want to enumerate with the return value of File.ReadLines:

    var lines = File.ReadAllLines("c:\\file.txt");
    foreach (var line in lines)
    {
        Console.WriteLine("\t" + line);
    }
    
    0 讨论(0)
  • 2020-12-05 18:31

    Change string[] lines = File.ReadLines("c:\\file.txt"); to IEnumerable<string> lines = File.ReadLines("c:\\file.txt"); The rest of your code should work fine.

    0 讨论(0)
提交回复
热议问题