Question

I have a method running with the following code:

private void WriteToDb()
{
    using (SqlConnection dbConnection = new SqlConnection(_conStr))
    {
        dbConnection.Open();
        using (SqlBulkCopy sbc = new SqlBulkCopy(_conStr))
        {
            sbc.DestinationTableName = "tblLog";
            try
            {
                sbc.WriteToServer(_tblLog);
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("{0} Error writing log info: {1} \n {3}", DateTime.Now.ToString(), e.Message, e.StackTrace));
            }
        }
    }

    _tblLog.Rows.Clear();
}

I am receiving an exception from the String.Format() method with the following stack trace:

Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list. at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) at System.String.Format(IFormatProvider provider, String format, Object[] args) at System.String.Format(String format, Object arg0, Object arg1, Object arg2) at MyCompany.MyClient.MySoftware.Logger.WriteToDb()

I can really see the source of this error. As far as I see I am not using any collection in that method. I also have to munch that this method is multi-threaded, but again I could not think of a possible impact.

Thank you!

Was it helpful?

Solution

Console.WriteLine(String.Format("{0} Error writing log info: {1} \n {3}", DateTime.Now.ToString(), e.Message, e.StackTrace));

Should be

Console.WriteLine(String.Format("{0} Error writing log info: {1} \n {2}", DateTime.Now.ToString(), e.Message, e.StackTrace));

OTHER TIPS

Your last format number is {3} instead of {2}

You're using {3} instead of {2}:

Console.WriteLine(String.Format("{0} Error writing log info: {1} \n {2}", DateTime.Now.ToString(), e.Message, e.StackTrace));

As far as I see I am not using any collection in that method.

System.String.Format(String format, Object arg0, Object arg1, Object arg2) calls System.String.Format(IFormatProvider provider, String format, Object[] args) so thats where the Collection comes into the stack.

As others explained you are using {3} but the array has only three elements, at index 0 through 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top