Power-Mosfet Power-Mosfet - 1 month ago 16
C# Question

C# how to split text file in multi files

How do I split a single text file with 1000 lines into multiple smaller files of, for example, 300 lines apiece? Please keep in mind that the original file may have more or less than a thousand lines.

file1.txt 300 lines -> rest
file2.txt 300 lines -> rest
file3.txt 300 lines -> rest
file4.txt 100 lines


I tried the following but it's not working.

int counter = 0;
string line;

string lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");

System.IO.StreamReader inputfile;

inputfile = new System.IO.StreamReader(new_path);
while ((line = inputfile.ReadLine()) != null)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt", true);

string _replaceBackspace = ReplaceBackspace(read_file.ReadLine().ToLower());

using (StreamWriter writer = new StreamWriter(lineoutput, true))
{
if (counter == 5000)
{
counter = 0;
lineoutput = (current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".txt");
}
writer.WriteLine(line.ToLower());
}
counter++;
}

Answer
string baseName = current_dir + "\\" + DateTime.Now.ToString("HHmmss") + ".";

StreamWriter writer = null;
try
{
    using (StreamReader inputfile = new System.IO.StreamReader(new_path))
    {
        int count = 0;
        string line;
        while ((line = inputfile.ReadLine()) != null)
        {

            if (writer == null || count > 300)
            {
                if (writer != null)
                {
                    writer.Close();
                    writer = null;
                }

                writer = new System.IO.StreamWriter(baseName + count.ToString() + ".txt", true);

                count = 0;
            }

            writer.WriteLine(line.ToLower());

            ++count;
        }
    }
}
finally
{
    if (writer != null)
        writer.Close();
}