当前位置: 首页>>代码示例>>C#>>正文


C# System.Net.WebClient.DownloadString方法代码示例

本文整理汇总了C#中System.Net.WebClient.DownloadString方法的典型用法代码示例。如果您正苦于以下问题:C# System.Net.WebClient.DownloadString方法的具体用法?C# System.Net.WebClient.DownloadString怎么用?C# System.Net.WebClient.DownloadString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


在下文中一共展示了System.Net.WebClient.DownloadString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ParsingTest_Should_Pass

        public void ParsingTest_Should_Pass()
        {
            var sb = new StringBuilder();
            var wc = new System.Net.WebClient();

            var cls = wc.DownloadString("https://raw.githubusercontent.com/furesoft/DynamicLanguageRuntime/master/DynamicLanguageRuntime/Library/System/Class.js");
            sb.AppendLine(cls);
            sb.AppendLine(wc.DownloadString("https://raw.githubusercontent.com/furesoft/DynamicLanguageRuntime/master/DynamicLanguageRuntime/Uri.js"));

            sb.AppendLine("var uri = new System.Uri('http://www.google.com/?s=hello');");
        }
开发者ID:furesoft,项目名称:DynamicLanguageRuntime,代码行数:11,代码来源:UriTest.cs

示例2: GetStopsByLocation

        public override List<Stop> GetStopsByLocation(double latitude, double longitude, double radius)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            var jsonResult = client.DownloadString("http://api.wmata.com/Rail.svc/json/JStations?api_key=" + APIKey);

            List<Stop> result = new List<Stop>();

            var data = Json.Decode(jsonResult);

            if (data != null)
            {
                foreach (var r in data.Stations)
                {
                    if (Utilities.Distance(latitude, longitude, Convert.ToDouble(r.Lat), Convert.ToDouble(r.Lon)) <= radius)
                    {
                        Stop s = new Stop();
                        s.ID = r.Code;
                        s.Name = r.Name;
                        s.Code = r.Code;
                        s.Latitude = Convert.ToDouble(r.Lat);
                        s.Longitude = Convert.ToDouble(r.Lon);

                        result.Add(s);
                    }
                }
            }

            jsonResult = client.DownloadString("http://api.wmata.com/Bus.svc/json/JStops?api_key=" + APIKey + "&lat=" + latitude + "&lon=" + longitude + "&radius=" + radius);

            data = Json.Decode(jsonResult);

            if (data != null)
            {
                foreach (var r in data.Stops)
                {
                    Stop s = new Stop();
                    s.ID = r.StopID;
                    s.Name = r.Name;
                    s.Code = r.StopID;
                    s.Latitude = Convert.ToDouble(r.Lat);
                    s.Longitude = Convert.ToDouble(r.Lon);

                    result.Add(s);
                }
            }

            return result;
        }
开发者ID:mbmccormick,项目名称:OneTransitAPI,代码行数:48,代码来源:WMATA.cs

示例3: Parse

        private static void Parse(string url)
        {
            List<string> srTgs = new List<string>();
            System.Net.WebClient cl = new System.Net.WebClient();
               // cl.BaseAddress = url;
            var siteData = cl.DownloadString(url);

            bool tagKick = false;
            string tagBuild = string.Empty;
            foreach (var c in siteData)
            {
                Console.WriteLine(c);
                if (c == '<')
                {
                    tagKick = true;

                }
                else if (tagKick == true && c == '>')
                {
                    tagBuild += c;
                    tagKick = false;
                }
                if (tagKick)
                {
                    tagBuild += c;
                }
                if (!string.IsNullOrWhiteSpace(tagBuild) && !tagKick)
                {
                    srTgs.Add(tagBuild);
                    tagBuild = string.Empty;
                }
            }
        }
开发者ID:pankajdey198320,项目名称:MYRND,代码行数:33,代码来源:Program.cs

示例4: Initialize

        public override void Initialize()
        {
            string path = Path.Combine(TShock.SavePath, "CodeReward1_9.json");
            Config = Config.Read(path);
            if (!File.Exists(path))
            {
                Config.Write(path);
            }
            Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "codereward"));
            Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "crt"));
            Variables.ALL = Config.ALL;

            //Events
            ServerApi.Hooks.ServerChat.Register(this, Chat.onChat);

            string version = "1.3.0.8 (1.9)";
            System.Net.WebClient wc = new System.Net.WebClient();
            string webData = wc.DownloadString("http://textuploader.com/al9u6/raw");
            if (version != webData)
            {
                Console.WriteLine("[CodeReward] New version is available!: " + webData);
            }

            System.Timers.Timer timer = new System.Timers.Timer(Variables.ALL.Interval * (60 * 1000));
            timer.Elapsed += run;
            timer.Start();
        }
开发者ID:TerraTeddy95,项目名称:CR,代码行数:27,代码来源:main.cs

示例5: DownloadString

        private static string DownloadString(string uri)
        {
            Thread.Sleep(5000);

            using (var wc = new System.Net.WebClient())
                return wc.DownloadString(uri);
        }
开发者ID:ZeroToHero-2015,项目名称:Fundamentals2016,代码行数:7,代码来源:SimpleDownloadingStringTask.cs

示例6: GetPlayerGames

        public SteamPlayerGames GetPlayerGames(string profileName)
        {
            var client = new System.Net.WebClient();
            string xml = client.DownloadString(string.Format(getPlayerGamesUrl, profileName));

            return SteamPlayerGames.Deserialize(xml);
        } 
开发者ID:KimimaroTsukimiya,项目名称:SteamBot-1,代码行数:7,代码来源:SteamWebClient.cs

示例7: btnSend_Click

 private void btnSend_Click(object sender, EventArgs e)
 {
     using (System.Net.WebClient client = new System.Net.WebClient())
     {
         try
         {
             string url = "http://smsc.vianett.no/v3/send.ashx?" +
                          "src=" + textPhoneNumber.Text + "&" +
                          "dst=" + textPhoneNumber.Text + "&" +
                          "msg=" +
                          System.Web.HttpUtility.UrlEncode(textMessage.Text,
                             System.Text.Encoding.GetEncoding("ISO-8859-1")) + "&" +
                          "username=" + System.Web.HttpUtility.UrlEncode(textUserName.Text) + "&" +
                          "password=" + System.Web.HttpUtility.UrlEncode(textPassword.Text);
             string result = client.DownloadString(url);
             if (result.Contains("OK"))
                 MessageBox.Show("Your message has been successfully sent.", "Message", MessageBoxButtons.OK,
                     MessageBoxIcon.Information);
             else
                 MessageBox.Show("Your message was not successfully delivered", "Message", MessageBoxButtons.OK,
                     MessageBoxIcon.Information);
         }
         catch (Exception ex)
         { 
         
                 MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
             
         }
     }
 }
开发者ID:lukekavanagh,项目名称:SeedyTextSender,代码行数:30,代码来源:Form1.cs

示例8: GetStopTimes

        public override List<StopTime> GetStopTimes(string stopID)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            var jsonResult = client.DownloadString("http://api.onebusaway.org/api/where/arrivals-and-departures-for-stop/" + stopID + ".json?key=" + APIKey + "&version=2");

            List<StopTime> result = new List<StopTime>();

            var response = Json.Decode(jsonResult).data;

            foreach (var r in response.entry.arrivalsAndDepartures)
            {
                StopTime t = new StopTime();
                t.RouteShortName = r.routeShortName;
                t.RouteLongName = r.routeLongName;
                if (r.predicted.ToString().ToLower() == "true")
                {
                    t.ArrivalTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.predictedArrivalTime.ToString()).TimeOfDay;
                    t.DepartureTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.predictedDepartureTime.ToString()).TimeOfDay;
                    t.Type = "realtime";
                }
                else
                {
                    t.ArrivalTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.scheduledArrivalTime.ToString()).TimeOfDay;
                    t.DepartureTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.scheduledDepartureTime.ToString()).TimeOfDay;
                    t.Type = "scheduled";
                }

                if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2)
                    result.Add(t);
            }

            return result;
        }
开发者ID:mbmccormick,项目名称:OneTransitAPI,代码行数:33,代码来源:Seattle.cs

示例9: GetStringFromURL

        internal string GetStringFromURL(string URL)
        {
            string cacheKey = string.Format("GetStringFromURL_{0}", URL);
            var cached = CacheProvider.Get<string>(cacheKey);
            if (cached != null)
            {
                LogProvider.LogMessage("Url.GetStringFromURL  :  Returning cached result");
                return cached;
            }

            LogProvider.LogMessage("Url.GetStringFromURL  :  Cached result unavailable, fetching url content");

            var webClient = new System.Net.WebClient();
            string result;
            try
            {
                result = webClient.DownloadString(URL);
            }
            catch (Exception error)
            {
                if (LogProvider.HandleAndReturnIfToThrowError(error))
                    throw;
                return null;
            }

            CacheProvider.Set(result, cacheKey);
            return result;
        }
开发者ID:DinisCruz,项目名称:GithubSharp,代码行数:28,代码来源:Url.cs

示例10: GetReportByCriteria

        public static List<Report> GetReportByCriteria(string lang, string term, string ageRange, string gender, string seriousReport)
        {
            var items = new List<Report>();
            var filteredList = new List<Report>();
            var json = string.Empty;
            var drugname = term;
            var adverseReaction = term;
            //var reportJsonUrl = string.Format("{0}&drugname={1}&lang={2}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, lang);
            var reportJsonUrl = string.Format("{0}&drugname={1}&ageRange={2}&gender={3}&seriousReport={4}&lang={5}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, ageRange, gender, seriousReport, lang);
            //var reportJsonUrl = string.Format("{0}&drugname={1}&adverseReaction={2}&lang={3}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, adverseReaction, lang);
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    webClient.Encoding = Encoding.UTF8;
                    json = webClient.DownloadString(reportJsonUrl);
                    if (!string.IsNullOrWhiteSpace(json))
                    {
                        items = JsonConvert.DeserializeObject<List<Report>>(json);
                    }
                }
            }
            catch (Exception ex)
            {
                var errorMessages = string.Format("UtilityHelper - GetReportByCriteria()- Error Message:{0}", ex.Message);
                ExceptionHelper.LogException(ex, errorMessages);
            }
            finally
            {

            }
            return items;
        }
开发者ID:hres,项目名称:api-cvp,代码行数:33,代码来源:UtilityHelper.cs

示例11: GetAllReportList

        public static List<Report> GetAllReportList(string lang)
        {
            var items = new List<Report>();
            var filteredList = new List<Report>();
            var json = string.Empty;

            // var postData = new Dictionary<string, string>();
            var dpdJsonUrl = string.Format("{0}&lang={1}", ConfigurationManager.AppSettings["dpdJsonUrl"].ToString(), lang);

            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    json = webClient.DownloadString(dpdJsonUrl);
                    if (!string.IsNullOrWhiteSpace(json))
                    {
                        items = JsonConvert.DeserializeObject<List<Report>>(json);

                    }
                }
            }
            catch (Exception ex)
            {
                var errorMessages = string.Format("UtilityHelper - GetJSonDataFromDPDAPI()- Error Message:{0}", ex.Message);
                ExceptionHelper.LogException(ex, errorMessages);
            }
            finally
            {

            }
            return items;
        }
开发者ID:hres,项目名称:api-cvp,代码行数:32,代码来源:UtilityHelper.cs

示例12: GetOwnedGames

        public IList<Game> GetOwnedGames(string steamId)
        {
            const string serviceUrl = "/IPlayerService/GetOwnedGames/v0001/?key={0}&steamId={1}&include_appinfo=1&include_played_free_games=1&format=json";
            const string pictureUrl = "http://media.steampowered.com/steamcommunity/public/images/apps/{0}/{1}.jpg";
            const string storeUrl = "http://store.steampowered.com/app/{0}";

            var url = string.Format(SteamApiBaseUrl + serviceUrl, Key, steamId);
            var webclient = new System.Net.WebClient() { Encoding = System.Text.Encoding.UTF8 };

            var jsonData = webclient.DownloadString(url);

            var o = JObject.Parse(jsonData);

            if (!o["response"].Any()) return null; // Will happen if the profile isn't public

            if (o["response"]["game_count"].Value<int>() == 0) return new List<Game>(); // Will happen if the profile has no games at all

            var a = o["response"]["games"].Select(g => new Game
                {
                    AppId = (int)g["appid"],
                    Name = (string)g["name"],
                    HoursPlayed = g["playtime_forever"] == null ? null : (int?)Math.Round((double)g["playtime_forever"] / 60, 0), // Playtime is expressed in minutes but we want hours
                    IconUrl = string.Format(pictureUrl, g["appid"], g["img_icon_url"]),
                    LogoUrl = string.IsNullOrEmpty((string)g["img_logo_url"]) ? "Content/images/nocover.png" : string.Format(pictureUrl, g["appid"], g["img_logo_url"]),
                    StoreUrl = string.Format(storeUrl, g["appid"])
                });

            return a.ToList();
        }
开发者ID:scarpentier,项目名称:SteamParty,代码行数:29,代码来源:SteamApi.cs

示例13: initDictionar

        private void initDictionar()
        {
            dictionar = new Dictionary<string, Country>();
            string xmlStr;
            using (var wc = new System.Net.WebClient())
            {
                xmlStr = wc.DownloadString(url);
            }
            var xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlStr);

            XmlNodeList countries = xmlDoc.GetElementsByTagName("country");

            foreach (XmlNode country in countries)
            {
                if (country.HasChildNodes)
                {

                    string name = country["countryName"].InnerText;
                    string code = country["countryCode"].InnerText;
                    string continent = country["continent"].InnerText;
                    double population = Convert.ToDouble(country["population"].InnerText);
                    double area = Convert.ToDouble(country["areaInSqKm"].InnerText);

                    Country ct = new Country(area, population, name, code, continent);

                    dictionar.Add(name, ct);

                }
            }
        }
开发者ID:RaduGabriel,项目名称:MeAd,代码行数:31,代码来源:Classes.cs

示例14: LoadBlocks

        /// <summary>
        /// Loads the blocks.
        /// </summary>
        /// <returns>Dictionary containing the blocks with their respective ids and colors.</returns>
        /// <exception cref="InvalidDataException">
        /// The blocks did not download correctly.
        /// or
        /// The blocks are not in the correct format.
        /// </exception>
        public static Dictionary<string, Color> LoadBlocks()
        {
            // if the acorn file does not exist...
            string text = null;
            using (var wc = new System.Net.WebClient())
                text = wc.DownloadString("https://raw.githubusercontent.com/Tunous/EEBlocks/master/Colors.txt");

            if (text == null)
                throw new InvalidDataException("The blocks did not download correctly.");

            if (!text.StartsWith("ID: 0 Mapcolor: "))
                throw new InvalidDataException("The blocks are not in the correct format.");

            text = text.Replace('\r', ' ');

            Dictionary<string, Color> blockDict = new Dictionary<string, Color>();

            string[] lines = text.Split('\n');
            for (int i = 0; i < lines.Length; i++) {
                if (lines[i].Length < 15)
                    continue;

                string[] line = lines[i].Split(' ');
                if (line.Length < 4 || line[0] != "ID:" || line[2] != "Mapcolor:")
                    throw new InvalidDataException("Incorrect block color format.");

                uint u32color = Convert.ToUInt32(line[3]);
                if (u32color == 0)
                    continue;

                blockDict.Add(line[1], UIntToColor(u32color));
            }

            return blockDict;
        }
开发者ID:SmallJoker,项目名称:Squirrel,代码行数:44,代码来源:Acorn.cs

示例15: Run

 public int Run(Cli console,string[] args)
 {
     string source = null;
     string local  = null;
     Options opts = new Options("Downloads a specified file")
     {
         new Option((string s)=>source =s,"address","The source address of the file to be downloaded"),
         new Option((string l)=>local =l,"localFile","Save the remote file as this name"),
     };
     opts.Parse(args);
     if(source == null)
     {
         return 1;
     }
     using(var client = new System.Net.WebClient())
     {
         if(local !=null)
         {
             client.DownloadFile(new Uri(source),local);
         }
         else
         {
             var result = client.DownloadString(new Uri(source));
             console.Out.WriteLine(result);
         }
     }
     return 0;
 }
开发者ID:jmaxxz,项目名称:Jmaxxz.Console,代码行数:28,代码来源:Download.cs


注:本文中的System.Net.WebClient.DownloadString方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。