How to Read Private Fields Through Reflection In .net

After a long while, no i am not in a mood to blog right now! lol but still i just wanted to share/save this code snippet here in my blog as i could’t  think of a better place :P

Basically this code works on dot net compact framework. and it was written so that i can read a table name that is stored inside a SQLCeResultSet object… this code uses reflection to archive this task :)

//load the assembly by the given name
Assembly asm = Assembly.Load(“System.Data.SqlServerCe”);
//get the type of MetaData the class that holds the needed field
Type MetaData = asm.GetType(“System.Data.SqlServerCe.MetaData”);
//get the Field info for the needed field, baseTableName
FieldInfo FIbaseTableName = MetaData.GetField(“baseTableName”, BindingFlags.Instance | BindingFlags.NonPublic);
//get the FieldInfo for the metadata property in the SQLCeDataReader class.
FieldInfo fi = typeof(SqlCeDataReader).GetField(“metadata”, BindingFlags.Instance | BindingFlags.NonPublic);
//get the metadata array
IList metadataArray = (IList)fi.GetValue(rsSeek);
//get the table name that we want
Debug.Assert(metadataArray.Count > 0);
string tableName = (string) FIbaseTableName.GetValue(metadataArray[0]);

thats it folks, i hope this would help someone out in the future(including my self :) ). read the comments if you have any doubts about how this works.

Leave a Reply