Sunday, August 21, 2011

C#: How to get the all the field/column names in a DataReader

The following helper method writes out the index position, the name and the data type for all the fields/columns in a DataReader, to the output window in Visual Studio:

public static void DataReaderDebugger(IDataReader reader)
{
 System.Diagnostics.Debug.WriteLine("### DataReader Debug Info ###");
 for (int i = 0; i < reader.FieldCount; i++)
 {
  string info = string.Format("{0}. {1} ({2})",
        i.ToString(),
        reader.GetName(i),
        reader.GetFieldType(i).Name);

  System.Diagnostics.Debug.WriteLine(info);
 }
 System.Diagnostics.Debug.WriteLine("######");
}