C# CommandTimeout Using statement issue

92 Views Asked by At

I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.

The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.

I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.

    public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
    {
        string logDirectory = VariableStorage.logDirectory;
        string Practice = VariableStorage.Practice;

        try
        {
            SqlConnection conn = new SqlConnection(connection);
            conn.Open();

            using (var command = new SqlCommand(QueryToExec, conn))
            using (var reader = command.ExecuteReader())

            using (var outFile = File.CreateText(destinationFile))
            {
                string[] columnNames = GetColumnNames(reader).ToArray();
                int numFields = columnNames.Length;
                outFile.WriteLine(string.Join("\t", columnNames));
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        string[] columnValues =
                            Enumerable.Range(0, numFields)
                                      .Select(i => reader.GetValue(i).ToString())
                                      .Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
                                      .ToArray();

                        outFile.WriteLine(string.Join("\t", columnValues));
                    }
                }
            }
        }
        catch (Exception e)
        {
            Program log = new Program();
            log.WriteToLog(" Error: " + e);
            SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
        }
    }
1

There are 1 best solutions below

0
On

OK, found the answer. I had to remove the Using statements.

            var command = new SqlCommand(QueryToExec, conn);
            command.CommandTimeout = 300;
            var reader = command.ExecuteReader();
            var outFile = File.CreateText(destinationFile);