将文件的前10行提取为字符串

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

如何在字符串中获取文件的前10行?

而不是直接使用StreamReader ,使用File.ReadLines返回IEnumerable 。 然后你可以使用LINQ:

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

使用File.ReadLines而不是File.ReadAllLines的好处是它只读取您感兴趣的行,而不是读取整个文件。 另一方面,它仅适用于.NET 4+。 如果你想要它用于.NET 3.5,那么使用迭代器块很容易实现。

ToList()的调用是为了强制查询(即实际读取数据),以便只读取一次。 如果没有ToList调用,如果你试图多次迭代first10Lines ,它会不止一次读取该文件(假设它完全有效;我似乎记得File.ReadLines在这方面没有得到非常干净的实现)。

如果你想将前10行作为单个字符串(例如用“\ r \ n”分隔它们),那么你可以使用string.Join

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

显然,您可以通过更改调用中的第一个参数来更改分隔符。

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

您可以尝试使用File.ReadLines 。 试试这个:-

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

在你的情况下尝试这个,因为你希望前10行作为单个字符串,所以你可以尝试使用string.Join()像这样:

 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(); 

这循环十次并将结果放在一个新的数组中。

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

要么

 public void skip10Lines() { int count=0; List lines=new List(); foreach(var line in File.ReadLines(path)) { if(count==10) break; lines.Add(line); count++; } } 

在基于JVM的语言Groovy中,一种方法是:

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

因为,闭包没有“中断”,所以循环嵌套在闭包中,因此Groovy运行时会处理资源处理。