简体   繁体   中英

How to write datatable rows to multiple files N number of records at a time?

I have a query that pulls an unknown number of rows in to a datatable. I need to write the datatable to multiple tabbed delimited text files with only 55 rows per file. Desired results Ex. 176 records from query. File1 - 55 records, File2 - 55 records, File3 - 55 records, File6 - 11 records. I am not sure the best way to do this. Any help would be greatly appreciated.

Current Code:

DataTable results = sql results;

if (results.Rows.Count > 0)
{
    int counter = 0;
    int maxRows = 55;
    string fileName = path + "File_" + today.ToString("yyyyMMdd") + ".txt";
    
    if (File.Exists(fileName))
    {
        File.Delete(fileName);
    }

    for (int i = 0; i < results.Rows.Count; i++)
    {
        var currentRow = results.Rows[i];                         

        _writer.WriteDataToFile(results, fileName, delimiter); //This method writes a datatable to a file
                                    
        counter = counter + i;
    }                           
} 

Try following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication190
{
    class Program
    {
        const string PATH = @"Enter Path Here";
        const int NUMBER_ROWS = 55;
        static void Main(string[] args)
        {

            DataTable results = new DataTable();
            DateTime today = DateTime.Now.Date;
            if (results.Rows.Count > 0)
            {
                int filenumber = 0;
                int rowCount = 0;
                StreamWriter writer = null;
                foreach (DataRow row in results.AsEnumerable())
                {
                    if (rowCount % NUMBER_ROWS == 0)
                    {
                        if (writer != null)
                        {
                            writer.Flush();
                            writer.Close();
                        }
                        string fileName = PATH + "File_" + ++filenumber + "_" + today.ToString("yyyyMMdd") + ".txt";
                        writer = new StreamWriter(fileName);
                    }
                    writer.WriteLine(string.Join("\t", row.ItemArray));
                    rowCount++;
                }
                writer.Flush();
                writer.Close()
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM