Stream Writer inside a loop

  • Thread starter Thread starter FcabralJ
  • Start date Start date
F

FcabralJ

Guest
I'm trying to write multiple files insie a loop where I read one file and split it depending on the number of rows. The issue is in the first loop where the file has not been written.

int i = 0;
int totalLoopLines = 1;
int blocks = 1;
var filePath = @"c:\test\cars.csv"
int rowsToSplit = 1000000;
int totalLines = File.ReadLines(filePath).Count();
var header = File.ReadLines(filePath).First();

StreamWriter sw = null;

var firstLine = true;

foreach (var line in File.ReadLines(filePath).Skip(1))
{
if (i >= rowsToSplit && totalLoopLines <= totalLines)
{
i = 0;
sw.Close();
sw.Dispose();
blocks += 1;
sw = new StreamWriter(directoryName + "\\" + fileName + "_" + (blocks * rowsToSplit) + ".csv");
sw.WriteLine(header);
sw.WriteLine(line);
}
else
{
if (firstLine)
{
sw = new StreamWriter(directoryName + "\\" + fileName + "_" + (blocks * rowsToSplit) + ".csv");
firstLine = false;
sw.WriteLine(header);
}

sw.WriteLine(line);
i++;

}

totalLoopLines += 1;

}

Continue reading...
 
Back
Top