Spliting text files into Multiple using LINQMSMurugavel S10yAsked Mar 16, 2016, 3:13 AM930Visual Basic .NETHow to split text files into multiple text files based on no. of lines by using LINQ C#?? ThanksMurugavels
MSMurugavel S10y agoPosted Mar 16, 2016, 4:37 AMHi Amit thnks for ur reply..but i need is have to create multiple files..i have achieved this by following code.. const string sourceFileName = @"\Test.txt"; const string destinationFileName = @"\Test{0}.txt"; const int linesPerFile = 50; using (var sourceFile = new StreamReader(sourceFileName)) { var fileCounter = 0; var destinationFile = new StreamWriter( string.Format(destinationFileName, fileCounter + 1)); try { var lineCounter = 0; string line; while ((line = sourceFile.ReadLine()) != null) { // Did we reach the maximum number of lines for the file? if (lineCounter >= linesPerFile) { // Yep... Time to close this one and // switch to another file lineCounter = 0; fileCounter++; destinationFile.Dispose(); destinationFile = new StreamWriter( string.Format(destinationFileName, fileCounter + 1)); } destinationFile.WriteLine(line); lineCounter++; } } finally { destinationFile.Dispose(); } } this is working fine.but i want to use linq to achieve this..can u help me.. 0
Amit Kumar Singh10y agoPosted Mar 16, 2016, 3:16 AM1.https://msdn.microsoft.com/en-us/library/bb546143.aspx0
Murugavel SPosted Mar 16, 2016, 4:37 AM
thnks for ur reply..
but i need is have to create multiple files..
const string sourceFileName = @"\Test.txt";
const string destinationFileName = @"\Test{0}.txt";
const int linesPerFile = 50;
using (var sourceFile = new StreamReader(sourceFileName))
{
var fileCounter = 0;
var destinationFile = new StreamWriter(
string.Format(destinationFileName, fileCounter + 1));
try
{
var lineCounter = 0;
string line;
while ((line = sourceFile.ReadLine()) != null)
{
// Did we reach the maximum number of lines for the file?
if (lineCounter >= linesPerFile)
{
// Yep... Time to close this one and
// switch to another file
lineCounter = 0;
fileCounter++;
destinationFile.Dispose();
destinationFile = new StreamWriter(
string.Format(destinationFileName, fileCounter + 1));
}
destinationFile.WriteLine(line);
lineCounter++;
}
}
finally
{
destinationFile.Dispose();
}
}
but i want to use linq to achieve this..
can u help me..
Amit Kumar SinghPosted Mar 16, 2016, 3:16 AM