Winform-根据当前IP获取所在城市名称

来源:互联网 发布:灵族女捏脸数据图 编辑:程序博客网 时间:2024/05/21 19:32

利用到天气预报的WebService,代码如下:

 public partial class frmMain : Form    {        WeatherWebService we;        IpAddressSearchWebService we1;        public frmMain()        {            InitializeComponent();        }        private void frmMain_Load(object sender, EventArgs e)        {            try            {                                we = new WeatherWebService();                    we1 = new IpAddressSearchWebService();                string locality = we1.getCountryCityByIp(GetIP())[1];                string city = locality.Substring(locality.IndexOf('省') + 1, locality.IndexOf('市') - (locality.IndexOf('省') + 1));                WeatherShow(we.getWeatherbyCityName(city));            }            catch (System.Exception ex)            {            }        }        private void WeatherShow(string[] strWeather)        {            labelTitle.Text = string.Format(strWeather[1]);               }        public static string GetIP()        {            using (var webClient = new WebClient())            {                try                {                    var temp = webClient.DownloadString("http://iframe.ip138.com/ic.asp");                    var ip = Regex.Match(temp, @"\[(?<ip>\d+\.\d+\.\d+\.\d+)]").Groups["ip"].Value;                    return !string.IsNullOrEmpty(ip) ? ip : null;                }                catch (Exception ex)                {                    return ex.Message;                }            }        }    }

效果如图:


源代码下载

0 0