13
public void get10FirstLines()
{ 
     StreamReader sr = new StreamReader(path);
     String lines = "";
     lines = sr.readLine();
}

How can I get the first 10 lines of the file in the string?

2
  • 2
    Your question isn't terribly clear - your method is calling skip10Lines which isn't the same as getting the first 10 lines into a string. It's also unclear whether you really want the lines in a single string or as a list.
    – Jon Skeet
    Feb 23, 2014 at 9:50
  • If this is from ypur real code: path should really be a parameter.
    – H H
    Feb 23, 2014 at 10:35

8 Answers 8

36

Rather than using StreamReader directly, use File.ReadLines which returns an IEnumerable<string>. You can then use LINQ:

var first10Lines = File.ReadLines(path).Take(10).ToList();

The benefit of using File.ReadLines instead of File.ReadAllLines is that it only reads the lines you're interested in, instead of reading the whole file. On the other hand, it's only available in .NET 4+. It's easy to implement with an iterator block if you want it for .NET 3.5 though.

The call to ToList() is there to force the query to be evaluated (i.e. actually read the data) so that it's read exactly once. Without the ToList call, if you tried to iterate over first10Lines more than once, it would read the file more than once (assuming it works at all; I seem to recall that File.ReadLines isn't implemented terribly cleanly in that respect).

If you want the first 10 lines as a single string (e.g. with "\r\n" separating them) then you can use string.Join:

var first10Lines = string.Join("\r\n", File.ReadLines(path).Take(10));

Obviously you can change the separator by changing the first argument in the call.

1
  • 1
    very nice solution, I would recommend putting it behind an abstraction for testablity.
    – Gent
    Feb 23, 2014 at 18:25
6
var lines = File.ReadAllLines(path).Take(10);
4
  • If user reads a 2 GB(9999 lines) file and only wants first 10 lines, would it access to only first 10 lines? Feb 23, 2014 at 9:47
  • @huseyintugrulbuyukisik: No, it would read everything - hence my answer.
    – Jon Skeet
    Feb 23, 2014 at 9:48
  • 2
    File.ReadLines() could be a very big optimization here.
    – H H
    Feb 23, 2014 at 9:48
  • thank you guys for answering. the thing is, i need it to be in a String. because im going to g.drawline() it afterwards. it cannot be a iterator. it needs to go directly into a string. String myString = ""; Feb 23, 2014 at 9:52
5

You may try to use File.ReadLines. Try this:-

var lines = File.ReadLines(path).Take(10);

In your case try this as you want the first 10 lines as a single string so you may try to use string.Join() like this:

var myStr= string.Join("", File.ReadLines(path).Take(10));
1
  • Instead of "" one should use string.Empty
    – Gistiv
    Nov 20, 2019 at 7:21
3
StringBuilder myString = new StringBuilder();

TextReader sr = new StreamReader(path);

for (int i=0; i < 10; i++)
{
myString.Append(sr.ReadLine())
}
2
String[] lines = new String[10];
for (int i = 0; i < 10; i++)
     lines[i] = sr.readLine();

That loops ten times and places the results in a new array.

0
public void skip10Lines()
{ 
    StringBuilder lines=new StringBuilder();
    using(StreamReader sr = new StreamReader(path))
    {
     String line = "";
     int count=0;

      while((line= sr.ReadLine())!=null)
      {
         if(count==10)
           break;
         lines.Append(line+Environment.NewLine);
         count++;
      }
     }

 string myFileData=lines.ToString();
 }

OR

public void skip10Lines()
{ 
     int count=0;
     List<String> lines=new List<String>();
     foreach(var line in File.ReadLines(path))
     {
         if(count==10)
           break;
         lines.Add(line);
         count++;
     }
 }
1
  • 1
    This won't compile (ReadLine, not readLine) and it's not closing the reader at the end.
    – Jon Skeet
    Feb 23, 2014 at 9:49
0

Reason beeing is that the nested operators File.ReadLines(path).Take(10).ToList(); will do the following truly:

string[] lines = File.ReadLines(path); // reads all lines of the file
string[] selectedlines = lines.Take(10); // takes first 10 line s into a new array
List<String> LinesList = selectedlines.ToList();

Especially the first part is cumbersome as it reads the full file into an enumerable of lines. This eats Performance and Memory. The question poster asked specifically for large files.

for this reason, I would rather recommend:

/// <summary>
/// This function loads and returns the first x lines from a file
/// </summary>
/// <param name="path">The path to the file to read</param>
/// <param name="amountOfLines">the number of lines which should be read</param>
/// <param name="encoding">optional value, which specifies the format in which the text file is saved</param>
/// <returns></returns>
public List<string> GetFirstXLines(string path, int amountOfLines, Encoding encoding = null)
{
    // if no encoding is set, try the default encoding (File Format)
    if (encoding == null) encoding = Encoding.Default;
    // create list which will be filled with the lines and returned later
    List<string> lines = new List<string>();
    // wrap streamreader around so it gets closed+disposed properly later
    using (StreamReader reader = new StreamReader(path, encoding))
    {
        // loop x times to get the first x lines
        for (int i = 0; i < amountOfLines; i++)
        {
            // read the next line
            string line = reader.ReadLine();
            // if the line is null, we are at the end of file, break out of the loop
            if (line == null) break;
            // if the line was not null, add it to the lines list
            lines.Add(line);
        }
    }
    // return the lines
    return lines;  
}
-1

In Groovy, a JVM based language, one approach is:

def buf = new StringBuilder()

Iterator iter = new File(path).withReader{
    for( int cnt = 0;cnt < 9;cnt++){    
        buf << it.readLine()
    }
}

println buf

Since, there is no 'break' from a closure, the loop is nested within the closure, and thereby the resource handling is taken care of by the Groovy runtime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.