Following a question I asked and the advice on SO I implemented the following solution. Are there any downsides to such a solution? Is there a better way to make it changeable when I need to control formatting of other types like double
and float
where I have more than one occurrence of each in the dataLine[]
?
public void Save(DataTable newMyDataTable)
{
String dateTimeFormat = "yyyy-MM-dd HH:mm:ss";
try
{
lock (writtingLock)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
dataTable = newMyDataTable;
fileId = dataTable.TableName;
PathMaker path = new PathMaker(fileId);
path.Make();
// writing the table to a file
using (StreamWriter swr =
new StreamWriter(File.Open(path.filePath, FileMode.Create), Encoding.Default, 1000000))
// change buffer size and Encoding to your needs
{
if (addHeader)
{
foreach (var dc in dataTable.Columns)
{
swr.Write(dc.ToString() + ",");
}
swr.WriteLine();
}
foreach (DataRow dr in dataTable.Rows)
{
Object[] dataLine = dr.ItemArray;
// extract date time and format it
var dateTime = dataLine.Where(o => o.GetType() == typeof(DateTime)).Select(t => (DateTime)t).Select(x => x.ToString(dateTimeFormat)).ToArray();
// collect data other than date time
var otherData = dataLine.Where(o => o.GetType() != typeof(DateTime)).ToArray();
// build your string
string dateTimeToWrite = string.Join(",", dateTime);
string otherDataToWrite = string.Join(",", otherData.Select(x => x.ToString().TrimEnd(null)).ToArray());
string lineToWrite = dateTimeToWrite + "," + otherDataToWrite;
swr.WriteLine(lineToWrite);
}
}
}
}