コード例 #1
0
        private static async Task <ServerStatus> GetServerStatus()
        {
            string content = null;

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    content = await Task.Run(() => webClient.DownloadString(new Uri(URL)));
                }
            }
            catch (Exception e)
            {
                //cannot reach url
                return(ServerStatus.ServerStatusError("err:url\n" + e));
            }


            //cannot get html content
            if (content == null)
            {
                return(ServerStatus.ServerStatusError("err:dl"));
            }

            var doc = new HtmlDocument();

            doc.LoadHtml(content);

            string text_status   = "";
            string text_nbPlayer = "";
            int    nbPlayer      = 0;

            try
            {
                text_status = doc.DocumentNode.Descendants()
                              .Where((n) => n.HasClass("status"))
                              .First().Descendants().ElementAt(1).InnerText;
                //WriteLog("SERV_STATUS : " + text_status);
            }
            catch (Exception e)
            {
                return(ServerStatus.ServerStatusError("err:html_status\n" + e));
            }

            try
            {
                text_nbPlayer = doc.DocumentNode.Descendants()
                                .Where((n) => n.HasClass("info-label")).First().InnerText;
                //WriteLog("SERV_NB_PLAYER : " + text_nbPlayer);
                text_nbPlayer = text_nbPlayer.Split('/')[0];
            }
            catch (Exception e)
            {
                return(ServerStatus.ServerStatusError("err:html_nbPlayer\n" + e));
            }

            if (text_status != "Online" && text_status != "Offline")
            {
                return(ServerStatus.ServerStatusError("err:text_status"));
            }

            if (!int.TryParse(text_nbPlayer, out nbPlayer))
            {
                return(ServerStatus.ServerStatusError("err:text_nbPlayer (=" + text_nbPlayer + ")"));
            }

            if (text_status == "Online")
            {
                return(ServerStatus.ServerStatusOnline(nbPlayer));
            }
            else
            {
                return(ServerStatus.ServerStatusOffline());
            }
        }