Sunday 10 July 2011

System.Configuration.ConfigurationSettings.AppSettings’ is obsolete: ‘This method is obsolete, it has been replaced by System.Configuration!System.Con

one of the great ways to save machine/server specific info into application is to save it in app.config or web.config file. these config files traditionally stores connection informations to the database. But how about if you want to store some other things like, the location of input and output folder for files.
below is a code snippet of two file locations that i am storing into app.config file
as you can probably understand i have created two key value pairs named "Source" and "Assembly" which stores a file location of my computer. now question is how to get them in your .cs file? answer is, use "ConfigurationSettings" class under system. so if you want to the value "source" in .cs just type in this
string k = ConfigurationSettings.AppSettings["Source"].ToString();
but as soon as you type that in, if you are using .net 4.0 you are going to encounter the second problem. the line will be underlined in green which will say some thing like,
System.Configuration.ConfigurationSettings.AppSettings’ is obsolete: ‘This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings
so then you will likely be using "ConfigurationManager" instead. now you face the third problem. it will say, "ConfigurationManager does not exists in current context" [i do not have clue why this sentence cannot be some thing like this "We cannot find the damn thing. check your references"]
Since "ConfigurationSettings" came under intelli-sense without referencing anything, logical deduction was i will see "ConfigurationManager" in the same list since both of them belong to System.Configuration. i googled it a lot and found out that you have to manually reference System.ConfigurationManager into the application. "why on earth you have to do this for Manager and do not have to do it for settings" is something i yet to discover.
So once you reference "System.ConfigurationManager" all will become cake walk to you. and the final code for getting the value of "Source" will be,
source = ConfigurationManager.AppSettings["Source"].ToString();

No comments: