按C#中的行数将大文件拆分为较小的文件?

我试图弄清楚如何按每个文件中的行数拆分文件。 文件是csv,我不能按字节来完成。 我需要按行来做。 每个文件20k似乎是一个很好的数字。 在给定位置读取流的最佳方法是什么? Stream.BaseStream.Position? 所以,如果我读了前20k行,我会在39,999开始这个位置? 我怎么知道我几乎在文件的末尾? 谢谢大家

using (System.IO.StreamReader sr = new System.IO.StreamReader("path")) { int fileNumber = 0; while (!sr.EndOfStream) { int count = 0; using (System.IO.StreamWriter sw = new System.IO.StreamWriter("other path" + ++fileNumber)) { sw.AutoFlush = true; while (!sr.EndOfStream && ++count < 20000) { sw.WriteLine(sr.ReadLine()); } } } } 
 int index=0; var groups = from line in File.ReadLines("myfile.csv") group line by index++/20000 into g select g.AsEnumerable(); int file=0; foreach (var group in groups) File.WriteAllLines((file++).ToString(), group.ToArray()); 

我这样做:

 // helper method to break up into blocks lazily public static IEnumerable> SplitEnumerable (IEnumerable Sequence, int NbrPerBlock) { List Group = new List(NbrPerBlock); foreach (T value in Sequence) { Group.Add(value); if (Group.Count == NbrPerBlock) { yield return Group; Group = new List(NbrPerBlock); } } if (Group.Any()) yield return Group; // flush out any remaining } // now it's trivial; if you want to make smaller files, just foreach // over this and write out the lines in each block to a new file public static IEnumerable> SplitFile(string filePath) { return File.ReadLines(filePath).SplitEnumerable(20000); } 

这对你来说还不够吗? 你提到从一个位置移动到另一个位置,但我不明白为什么这是必要的。