33

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 at string[] lines = File.ReadLines("c:\\file.txt"); with cannot implicitly convert....

Can someone please advise on the codes to save the results in an array format? I've placed the ReadAllLines code which is able to save the results in an array too. Thanks!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Testing
{
class Analysis
{
    static void Main()
    {
        string[] lines = File.ReadLines("c:\\file.txt");

        foreach (string r in lines)
        {
            Console.WriteLine("-- {0}", r);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
}

ReadAllLines Codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace Testing
{
class ReadFromFile
{
    static void Main()
    {
        string[] lines = System.IO.File.ReadAllLines
        (@"C:\Users\Public\TestFolder\WriteLines2.txt");

        System.Console.WriteLine("Contents of writeLines2.txt =:");
        foreach (string line in lines)
        {
            Console.WriteLine("\t" + line);
        }

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
}
John Smith
  • 7,243
  • 6
  • 49
  • 61
JavaNoob
  • 3,494
  • 19
  • 49
  • 61

4 Answers4

55

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, such as IList<String>.

John Smith
  • 7,243
  • 6
  • 49
  • 61
Gerald Davis
  • 4,541
  • 2
  • 31
  • 47
  • ReturnLines is not a defination. That's what the system is showing. – JavaNoob Nov 19 '10 at 00:33
  • Ah I see my typo now. I updated the answer it should be ReadLines. The point is if you need an array use ReadAllLines(). If you can use a collection ReadLines() works better on large files because individual lines are only pulled when needed. – Gerald Davis Nov 19 '10 at 15:06
  • 1
    Yup thats kinda of the idea to allow a larger file to be used in ReadLines. So the above codes is not similar to ReadAllLines right? – JavaNoob Nov 19 '10 at 17:04
  • Right. The actual read occurs when the specific line is needed. The exact mechanics are opaque I have noticed on some small files ReadLines actually reads all the lines at once. Likely in the implementation there is some optimization where instead of a single line read at once some "block" of lines is read into the collection. – Gerald Davis Nov 19 '10 at 17:51
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.ReadLines("c:\\file.txt");
foreach (var line in lines)
{
    Console.WriteLine("\t" + line);
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • The reason for using Readlines instead of ReadAllLines is due to the file size. It is advisable for large text files as it might cause an buffer to overflow. – JavaNoob Nov 19 '10 at 00:22
  • 4
    But calling `ToArray` will negate any benefit of calling `ReadLines`. Use the enumerator as I showed. – Jim Mischel Nov 19 '10 at 00:24
  • Does the enumerator utilize the functions of ReadLines? – JavaNoob Nov 19 '10 at 00:29
  • I don't know how the enumerator is implemented. The fact is that both read the entire file into memory. The difference between the two is that `ReadAllLines` reads the entire file into memory and then returns. `ReadLines` returns almost immediately, allowing you to begin enumerating while it continues to load the rest of the file in the background. I suspect, though, that the ultimate result is very close to the same amount of memory. If you want to prevent memory problems when reading a large text file, use `StreamReader` and read line-by-line. – Jim Mischel Nov 19 '10 at 00:39
  • 4
    @Jim: I'm pretty sure that `ReadLines` does read the file line-by-line using a `StreamReader` or similar. That's the whole point. – LukeH Nov 19 '10 at 01:09
  • @JavaNoob. The reason ReadLines works well on large files it is an abstraction. It may look like ReadLines reads ALL the lines and loads it into the collection but it isn't. ReadLines returns the collection and then individual lines are loaded as needed. If you ABSOLUTELY MUST have an array then just use ReadAllLines. Using ReadLines will return the collection but converting it to an array will require all the lines at once thus the collection the collection will pull all the lines from the file defeating the purpose of ReadLines(). – Gerald Davis Nov 19 '10 at 14:59
  • 1
    @LukeH: You're right. I stand corrected. The returned `IEnumerable` is a one-use object. If, for example, you enumerate all the lines and then call `Count()`, you'll get an `ObjectDisposedException`. I understand why, but I can see that causing some confusion if someone were to pass that `IEnumerator` to a method that was expecting to query it multiple times. – Jim Mischel Nov 19 '10 at 16:21
  • 1
    @JavaNoob: I was wrong about how `ReadLines` is implemented. It does not read the entire file into memory. You can use `ReadLines` to avoid the buffer overflow problems that you mentioned. – Jim Mischel Nov 19 '10 at 16:23
  • Yea thats the idea as someone referenced my codes to using framework 4 ReadLines. – JavaNoob Nov 19 '10 at 17:05
2

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.

Greg Sansom
  • 20,442
  • 6
  • 58
  • 76
-2
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace FileReader
{
    class Program
    {
        static void Main(string[] args)
        {
            var lines = File.ReadAllLines("D:/Text.txt").ToList();
            if(lines != null && lines.Count  > 0)
            {
                foreach(var line in lines)
                {
                    Console.WriteLine(line);
                }
            }
            Console.ReadKey();
        }
    }
}