C# - 将DateTime字段(带NaNo秒)写入文本文件(使用Streamwriter)

时间:2014-07-09 04:01:07

标签: c#

见下文,其中数据集从表中返回结果。

数据集返回的列是DATETIME,但是使用以下代码 - 写入文件时会删除NANO秒。

例如 资料来源:2014-01-01 01:23:55.596

什么写入文件是 输出数据:2014-01-01 01:23:55

所以我想调整下面的代码,以便NANO秒也打印到文件。

try
{
    using (OleDbConnection connection1 = new OleDbConnection(str_ConnectionString1))
    {
        OleDbCommand command = new OleDbCommand(queryString1, connection1);
        command.CommandTimeout = 0;
        connection1.Open();
        OleDbDataReader reader1 = command.ExecuteReader();

        // This size is just for example purpose. Should be fine tuned
        StreamWriter writer1 = new StreamWriter(@str_FeedFilePath1 + @str_FileName1);
        var result = string.Empty;
        StringBuilder buffer1 = new StringBuilder(1048576);
        while (reader1.Read())
        {
            for (int j = 0; j < reader1.FieldCount; j++)
            {
                buffer1.Append(reader1[j] + "|");
            }
            buffer1.AppendLine();
            if (buffer1.Length > 1048576 - 1024)
            {
                writer1.Write(buffer1.ToString());
                buffer1.Length = 0;
            }
        }
        writer1.Write(buffer1.ToString());
        writer1.WriteLine(result);
        reader1.Close();
        writer1.Close();

        Dts.TaskResult = (int)ScriptResults.Success;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要检查阅读器返回的对象。它看起来像这样:

if (reader1[j] is DateTime)
   buffer1.Append(((DateTime)reader1[j]).ToString("o"));
else
   buffer1.Append(reader1[j]);
buffer1.Append("|");
...

PS:DateTime仅精确到100ns,除非您使用的是MS的DateTime2字段,否则您可能比数据库中的精确度更低。你的意思是毫秒?