How to convert System.Web.Configuration.WebConfigurationManager.AppSettings from String to INT

In my web.config file, I defined the following: -

<add key="TechPageSize" value="20" /> 

But I cannot refer to this value in my paging parameters as follows: -

 var servers = repository.AllFindServers(withOutSpace).OrderBy(a => a.Technology.Tag).ToPagedList(page, (Int32)System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]); 

and I get an error that it cannot change String to INT.

Any idea what the problem is?

+6
source share
3 answers
 int techPageSize; if (!int.TryParse(ConfigurationManager.AppSettings["TechPageSize"], out techPageSize)) { throw new InvalidOperationException("Invalid TechPageSize in web.config"); } 

Int32.TryParse has two effects:

  • It converts the application parameter to an integer and stores the result in techPageSize , if possible.
  • If the value cannot be converted, the method returns False , which allows you to handle the error, as it seems to you.

PS: It’s enough to use ConfigurationManager.AppSettings once you have imported the System.Configuration namespace.

+11
source

Result

 System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"] 

is a string, you cannot just pass the string to int. Use Convert.ToInt32 or int.TryParse to get the integer value of the string.

 int pagesize = Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]); 

or

 bool succeed = int.TryParse(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"], out pagesize); 
+3
source

Try:

 Convert.ToInt32(System.Web.Configuration.WebConfigurationManager.AppSettings["TechPageSize"]) 

This will result in an error if the conversion fails. You can use int.Tryparse if it does not convert to int, but the fact is that it is a configuration setting, and only you have control over this value - it is not sent to users, so IMO will be unnecessary to provide an error.

+2
source

Source: https://habr.com/ru/post/958301/


All Articles