Well, for starters, you need to use File.ReadLines
(assuming you're using .NET 4) so ββthat it doesn't try to read all of this in memory. Then I just keep calling the method to spit the βnextβ number of lines into the new file:
int splitSize = Convert.ToInt32(txtNoOfLines.Text); using (var lineIterator = File.ReadLines(...).GetEnumerator()) { bool stillGoing = true; for (int chunk = 0; stillGoing; chunk++) { stillGoing = WriteChunk(lineIterator, splitSize, chunk); } } ... private static bool WriteChunk(IEnumerator<string> lineIterator, int splitSize, int chunk) { using (var writer = File.CreateText("file " + chunk + ".txt")) { for (int i = 0; i < splitSize; i++) { if (!lineIterator.MoveNext()) { return false; } writer.WriteLine(lineIterator.Current); } } return true; }
source share