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?

有帮助吗?

解决方案

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.

其他提示

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

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));
StringBuilder myString = new StringBuilder();

TextReader sr = new StreamReader(path);

for (int i=0; i < 10; i++)
{
myString.Append(sr.ReadLine())
}
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.

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++;
     }
 }

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;  
}

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top