如何一次将数据表行写入多个文件N条记录?
How to write datatable rows to multiple files N number of records at a time?
我有一个查询将未知数量的行提取到数据表中。我需要将数据表写入多个制表符分隔的文本文件,每个文件只有 55 行。期望的结果来自查询的 176 条记录。文件 1 - 55 条记录,文件 2 - 55 条记录,文件 3 - 55 条记录,文件 6 - 11 条记录。我不确定执行此操作的最佳方法。任何帮助将不胜感激。
当前代码:
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;
}
}
尝试以下操作:
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()
}
}
}
}
我有一个查询将未知数量的行提取到数据表中。我需要将数据表写入多个制表符分隔的文本文件,每个文件只有 55 行。期望的结果来自查询的 176 条记录。文件 1 - 55 条记录,文件 2 - 55 条记录,文件 3 - 55 条记录,文件 6 - 11 条记录。我不确定执行此操作的最佳方法。任何帮助将不胜感激。
当前代码:
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;
}
}
尝试以下操作:
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()
}
}
}
}