从web.config读取并格式化一个字符串

时间:2013-10-08 09:08:05

标签: c# asp.net

我从我的应用程序中排除了一些发送邮件的ipaddress。我在web.config文件中创建了自定义标签

<configSections>
  <sectionGroup name="ExcludeIPAddressListSectionGroup">
    <section name="IPAddressListSection" type="CustomConfigurationHandler.CustomConfiguration, CustomConfigurationHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowLocation="true" allowDefinition="Everywhere"/>
  </sectionGroup>
</configSections>

<ExcludeIPAddressListSectionGroup>
  <IPAddressListSection>
      <ExcludedList1 Range="StartingIP=192.168.185.1; EndingIP=192.168.185.50" ></ExcludedList1>
      <ExcludedList2 Range="StartingIP=192.168.185.51;EndingIP=192.168.185.51" ></ExcludedList2>
  </IPAddressListSection>
</ExcludeIPAddressListSectionGroup>

我创建了ExcludeIPAddressListSectionGroup部分和给定范围以排除那些ips

我正在读取web.config中的自定义标签

 Hashtable config = (Hashtable)ConfigurationManager.GetSection("ExcludeIPAddressListSectionGroup/IPAddressListSection");
 foreach (DictionaryEntry deKey in config)
 {
     Hashtable attribs = (Hashtable)deKey.Value;
     foreach (DictionaryEntry deAttrib in attribs)
     {
         string range = deAttrib.Value.ToString();
         string[] range_arr = range.Split(';');

         foreach (string range_str in range_arr)
         {
             Response.Write(range_str+"<br>");
         }
     }
 }

我需要格式化字符串并将startip和end ip传递给此函数bool Between(long value,long left,long right)

1 个答案:

答案 0 :(得分:0)

使用以下代码。它适用于IPV4。

        List<string> lstIPValues = new List<string>();
        foreach (string range_str in range_arr)
        {
             //again split to get ragne value into List of string.
            string[] ipValues = range_str.Split('=');
            lstIPValues.Add(ipValues[1]);    
        }
        Between(valueToBeChecked,, BitConverter.ToInt64(IPAddress.Parse(lstIPValues[0]).GetAddressBytes(), 0), BitConverter.ToInt64(IPAddress.Parse(lstIPValues[1]).GetAddressBytes(), 0));