Q:

Writing a million rows to a text file

Please see the below code which I use for writing to a text file. But database fetches nearly 1 millions records, so can someone please advise a faster way to do this or how should I change the below mentioned code to get it working faster?
try
{
    using (OleDbConnection connection = new OleDbConnection(ConnectionString))
    {
        OleDbCommand command = new OleDbCommand(queryString, connection);
        connection.Open();
        OleDbDataReader reader = command.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(reader);

        StreamWriter writer = new StreamWriter(FilePath + FileName);
        var result = string.Empty;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                result += dt.Rows[i][j] + "|";
            }
            result += "\r\n";
        }
        writer.WriteLine(result);

        reader.Close();
        writer.Close();

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

A:

You load 1 million records in a datatable and then loop again on that table to write each row.
Probably you could do the same thing, but in half the time if you read a single row and write it down:
OleDbDataReader reader = command.ExecuteReader();
StreamWriter writer = new StreamWriter(FilePath + FileName);
var result = string.Empty;
while(reader.Read())
{
    for (int j = 0; j < reader.FieldCount; j++)
    {
        result += reader[j] + "|";
    }
    result += "\r\n";
}
writer.WriteLine(result);

Also, using a StringBuilder to buffer your read in memory and not constantly writing to disk could be very beneficial in this situation:
// This size is just for example purpose. Should be fine tuned
StringBuilder buffer = new StringBuilder(1048576);
while(reader.Read())
{
    for (int j = 0; j < reader.FieldCount; j++)
    {
        buffer.Append(reader[j] + "|");
    }
    buffer.AppendLine();
    if(buffer.Length > 1048576 - 1024)
    {
        writer.Write(buffer.ToString());
        buffer.Length = 0;
    }
}
writer.Write(buffer.ToString());

