How to get the Names of all the columns from a SqlDataReader object in C# ?

Here’s a simple code snippet that demonstrates how to retreive all the column names from a SqlDataReader object in C#.

How to get the Names of all the columns from a SqlDataReader object in C# ?

public static List<string> GetColumnNames(SqlDataReader dataReader)
{
    List<string> columnNames = new List<string>();
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
        columnNames.Add(dataReader.GetName(i));
    }
    return columnNames;
}