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


C# WebClient.DownloadString方法代码示例

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


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

示例1: GitHubServiceTranslator

        public GitHubServiceTranslator(string username)
        {
            Errors = new List<KeyValuePair<string, string>>();
            Projects = new List<Project>();

            var webClient = new WebClient();

            try
            {
                var xmlSource = webClient.DownloadString(string.Format(userLookupUri, username));
                Projects = Projects.GetProjects(xmlSource);
                
                for (var i = 0 ; i < Projects.Count ; i++)
                {
                    var project = Projects[i];
                    var pageSource = webClient.DownloadString(string.Format(commitsLookupUri, username, project.Name));
                    project = project.GetDetails(pageSource);
                }

                Projects = GitHubServiceTranslatorExtensions.Clean(Projects);
            }
            catch (Exception ex)
            {
                Errors.Add(new KeyValuePair<string, string>("GitHubServiceTranslator", string.Format("Username {0} not found. Error: {1}", username, ex.Message)));
            }
        }
开发者ID:apavlo11356,项目名称:adamdotcom-services,代码行数:26,代码来源:GitHubServiceTranslator.cs

示例2: SparkleInviteOpen

        public SparkleInviteOpen(string url)
        {
            string safe_url   = url.Replace ("sparkleshare://", "https://");
            string unsafe_url = url.Replace ("sparkleshare://", "http://");
            string xml        = "";

            WebClient web_client = new WebClient ();

            try {
                xml = web_client.DownloadString (safe_url);

            } catch {
                Console.WriteLine ("Failed downloading invite: " + safe_url);

                try {
                    xml = web_client.DownloadString (safe_url);

                } catch {
                    Console.WriteLine ("Failed downloading invite: " + unsafe_url);
                }
            }

            string home_path   = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
            string target_path = Path.Combine (home_path, "SparkleShare");

            if (xml.Contains ("<sparkleshare>")) {
                File.WriteAllText (target_path, xml);
                Console.WriteLine ("Downloaded invite: " + safe_url);
            }
        }
开发者ID:neiljbrookes,项目名称:SparkleShare,代码行数:30,代码来源:sparkleshare-invite-opener.cs

示例3: Main

        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:5000/Service";
            ServiceHost host = new ServiceHost(typeof(TestService), new Uri(baseAddress));

            var webendpoint = host.AddServiceEndpoint(typeof(ITestService), new WebHttpBinding(), "");
            webendpoint.Behaviors.Add(new TypedUriTemplateBehavior());

            host.Open();
            Console.WriteLine("Host opened");

            WebClient c = new WebClient();

            #region Tests
            Console.WriteLine(c.DownloadString(baseAddress + "/" + Guid.NewGuid().ToString()));

            Console.WriteLine(c.DownloadString(baseAddress + "/Parent/" + 20));

            Console.WriteLine(c.DownloadString(baseAddress + "/" + Guid.NewGuid() + "/Current/" + 10));

            Console.WriteLine(c.DownloadString(baseAddress + "/Data/" + "Mein_name_ist_WCF"));
            #endregion

            Console.Read();
        }
开发者ID:BenAlabaster,项目名称:WebHttpBehaviorExtensions,代码行数:25,代码来源:Program.cs

示例4: pobierzdane

        private void pobierzdane(String wykonawca, String album)
        {
            WebClient klient = new WebClient();
            klient.Encoding = Encoding.UTF8;
            string content = "";
            string content2 = "";
            try
            {

                content = klient.DownloadString("http://en.wikipedia.org/wiki/" + album);
                //MessageBox.Show("http://en.wikipedia.org/wiki/" + album);
                content2 = klient.DownloadString("http://fm.tuba.pl/artysta/" + wykonawca);
                //MessageBox.Show("http://fm.tuba.pl/artysta/" + wykonawca);
                HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content);
                IEnumerable<HtmlNode> links = from link in doc.DocumentNode.Descendants()
                                              where link.Name == "th" && link.Attributes["class"] != null && link.Attributes["class"].Value == "summary album"
                                              select link;
                string tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label1.Text = tresc;
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "span" && link.Attributes["class"] != null && link.Attributes["class"].Value == "bday dtstart published updated"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label2.Text = tresc;
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "span" && link.Attributes["class"] != null && link.Attributes["class"].Value == "duration"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);

                label3.Text = tresc;

                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "a" && link.Attributes["class"] != null && link.Attributes["class"].Value == "image"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerHtml;
                //MessageBox.Show(tresc);
                String[] temp = tresc.Split('"');
                //MessageBox.Show(temp[3]);
                temp[3] = temp[3].Substring(2);
                //MessageBox.Show(temp[3]);
                cover.Load("http://" + temp[3]);

                doc = new HtmlAgilityPack.HtmlDocument();
                doc.LoadHtml(content2);
                links = from link in doc.DocumentNode.Descendants()
                        where link.Name == "p"
                        select link;
                tresc = links.ElementAt<HtmlNode>(0).InnerText;
                //MessageBox.Show(tresc);
                label5.Text = tresc;
            }
            catch (Exception e)
            {
                MessageBox.Show("Próba znalezienia szczegółów pliku nie powiodła się.");
            }
        }
开发者ID:bartoszzielinski,项目名称:musesort,代码行数:60,代码来源:SzczegolyMuzyki.cs

示例5: Main

        public static void Main()
        {
            Console.WriteLine("Connecting...");
            Console.WriteLine();
            var client = new WebClient();

            var albums = client.DownloadString("http://localhost:25099/api/albums/all");
            Console.WriteLine("Albums:");
            Console.WriteLine(albums);

            Console.WriteLine();
            Console.WriteLine("Adding albums...");
            Console.WriteLine();

            var albumPost = "{'Title': 'Nice Name', 'Year': '2014', 'Producer': 'Pesho'}";
            albumPost += "{'Title': 'Other Name', 'Year': '2013', 'Producer': 'Pesho'}";
            albumPost += "{'Title': 'Gosho ot po4ivka', 'Year': '2008', 'Producer': 'Pesho ot Pernik'}";
            albumPost += "{'Title': 'Zadushaam sa', 'Year': '2014', 'Producer': 'Bat Georgi'}";

            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.UploadString("http://localhost:25099/api/albums/create", albumPost);

            Console.WriteLine("Albums:");
            albums = client.DownloadString("http://localhost:25099/api/albums/all");
            Console.WriteLine(albums);

        }
开发者ID:d-kostov-dev,项目名称:Web-Services-And-Cloud-Course,代码行数:27,代码来源:EntryPoint.cs

示例6: GetExternalIP

        public static string GetExternalIP()
        {
            using (WebClient client = new WebClient()) {
                try {
                    string ip = client.DownloadString("http://canihazip.com/s");
                    if (ip == "77.174.16.28")
                        return "176.31.253.42";

                    return ip;
                }
                catch (WebException) {
                    // this one is offline
                }

                try {
                    return client.DownloadString("http://wtfismyip.com/text");
                }
                catch (WebException) {
                    // offline...
                }

                try {
                    return client.DownloadString("http://ip.telize.com/");
                }
                catch (WebException) {
                    // offline too...
                }

                // if we got here, all the websites are down, which is unlikely
                return "Check internet connection?";
            }
        }
开发者ID:westre,项目名称:Rootstamp-Server-Daemon,代码行数:32,代码来源:Utility.cs

示例7: buildJobInfo

        static void buildJobInfo(uint messageId, int currentMessageInstanceId)
        {
            WebClient webClient = new WebClient();
            webClient.Proxy = null;

            //The currentMessageInstanceId was obtained from basicMessageInfo().
            // We use limit == 1 to get max and min.  Note: limit == 0 will return all list results (if the request doesn't time out).
            string lastBuildJobUrl = string.Format("{0}/build-job-import/list-build-job-message-instance/messageInstanceId/{1}/limit/1/format/xml/sortField/buildJobId/sortDirection/DESC", getLciBaseUrl(), currentMessageInstanceId);
            string firstBuildJobUrl = string.Format("{0}/build-job-import/list-build-job-message-instance/messageId/{1}/limit/1/format/xml/sortField/buildJobId/sortDirection/ASC", getLciBaseUrl(), messageId);

            string lastBuildJobXmlString = webClient.DownloadString(lastBuildJobUrl);
            XmlDocument lastBuildJobDoc = new XmlDocument();
            lastBuildJobDoc.LoadXml(lastBuildJobXmlString);
            XmlNode lastBuildJobRootNode = lastBuildJobDoc.DocumentElement;

            //The subcomponent listed on the view message web page comes from the last build job
            Console.WriteLine("Subcomponent: " + getStringValueFromXmlNode(lastBuildJobRootNode, "item/componentName"));
            Console.WriteLine(string.Format("Last Build: {0} ({1})",
                getStringValueFromXmlNode(lastBuildJobRootNode, "item/buildJob/mainBuildArtifact/label"),
                getStringValueFromXmlNode(lastBuildJobRootNode, "item/buildJob/created")));

            string firstBuildJobXmlString = webClient.DownloadString(firstBuildJobUrl);
            XmlDocument firstBuildJobDoc = new XmlDocument();
            firstBuildJobDoc.LoadXml(firstBuildJobXmlString);
            XmlNode firstBuildJobRootNode = firstBuildJobDoc.DocumentElement;

            Console.WriteLine(string.Format("First Build: {0} ({1})",
                getStringValueFromXmlNode(firstBuildJobRootNode, "item/buildJob/mainBuildArtifact/label"),
                getStringValueFromXmlNode(firstBuildJobRootNode, "item/buildJob/created")));
        }
开发者ID:user222,项目名称:CmwebClientTest,代码行数:30,代码来源:Program.cs

示例8: CheckUpdatesThread

        private static UpdateResult CheckUpdatesThread()
        {
            string cver = CurrentVersion.major + "." + CurrentVersion.minor + "." + CurrentVersion.revision;
            Console.WriteLine("Check Updates.  Current Version: " + CurrentVersion.GetVersionString());
            System.Net.WebClient client = new WebClient();
            try
            {
                string response = client.DownloadString(updateDomain+"version.txt");
                Console.WriteLine("Got most recent version of flag '"+CurrentVersion.flags+"' from server: " + response);

                if (response.Trim() != cver.Trim()+CurrentVersion.flags)
                {
                    Console.WriteLine("New update available");
                    if(callback != null)
                        callback(UpdateResult.NewUpdate, client.DownloadString(updateDomain+"updatenotes.txt"), response.Trim());
                    return UpdateResult.NewUpdate;
                }
                else
                {
                    Console.WriteLine("No update available");
                    if (callback != null)
                        callback(UpdateResult.NoUpdates, "", "");
                    return UpdateResult.NoUpdates;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine("Update Check failed");
                Console.WriteLine(e.ToString());
                if (callback != null)
                    callback(UpdateResult.UnableToConnect, "", "");
                return UpdateResult.UnableToConnect;
            }
        }
开发者ID:anirnet,项目名称:raf-manager,代码行数:34,代码来源:Autoupdater.cs

示例9: aSyncSearchForModel

        private static IEnumerator aSyncSearchForModel(string filename, string searchterm)
        {
            WebClient w = new WebClient();
            string htmlstring = w.DownloadString("http://sketchup.google.com/3dwarehouse/doadvsearch?title=" + searchterm.Replace(" ","+")
                                        + "&scoring=d&btnG=Search+3D+Warehouse&dscr=&tags=&styp=m&complexity=any_value&file="
                                        + "zip" + "&stars=any_value&nickname=&createtime=any_value&modtime=any_value&isgeo=any_value&addr=&clid=");
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlstring);

            //Grab a result from the search page
            HtmlAgilityPack.HtmlNodeCollection results = doc.DocumentNode.SelectNodes("//div[@class='searchresult']");
            string model_page_url = "http://sketchup.google.com" + results[0].SelectSingleNode(".//a").Attributes["href"].Value;
            htmlstring = w.DownloadString(model_page_url);
            doc.LoadHtml(htmlstring);

            //Find the downloadable zip file
            results = doc.DocumentNode.SelectNodes("//a[contains(@href,'rtyp=zip')]");
            foreach (HtmlNode r in results)
            {
                HtmlAttribute src = r.Attributes["href"];
                string url = "http://sketchup.google.com" + src.Value;
                url = url.Replace("&amp;", "&");
                string location = @"path to downloads folder" + filename + ".zip";
                System.Diagnostics.Debug.WriteLine(url+"\n"+location);
                w.DownloadFile(new Uri(url),location);
            }
            return null;
        }
开发者ID:jrafferty3,项目名称:SketchupImporter,代码行数:28,代码来源:Program.cs

示例10: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            // extract the MusixMatch song ID from the query string
            int trackId = Convert.ToInt32(Request.QueryString["id"]);

            // initialize web client
            WebClient client = new WebClient();
            string response1 = client.DownloadString("http://api.musixmatch.com/ws/1.1/track.get?track_id=" + trackId + "&apikey=" + apiKey);

            // fetch the track information from MusixMatch
            var track = Json.Decode(response1).message.body.track;

            // output the track and artist name
            this.lblTitle.Text = track.track_name;
            this.lblArtist.Text = track.artist_name;

            // read the previously downloaded lyrics from disk
            StreamReader sr = new StreamReader(Server.MapPath("~/Data/" + track.track_id + ".txt"));
            this.lblLyrics.Text = sr.ReadToEnd().Replace("\n", "<br />\n");

            // download the Spotify embed component
            string response2 = client.DownloadString("http://ws.spotify.com/search/1/track.json?q=" + track.track_name);

            if (Json.Decode(response2).tracks.Count > 0)
            {
                // parse the Spotify URI for this song
                var spotifyUri = Json.Decode(response2).tracks[0].href;

                // output the Spotify embed component
                this.litPlayButton.Text = "<iframe src='https://embed.spotify.com/?uri=" + spotifyUri + "' width='400' height='480' frameborder='0' allowtransparency='true'></iframe>";
            }
        }
开发者ID:purdue-cs-groups,项目名称:cs490-WIR-project01,代码行数:32,代码来源:View.aspx.cs

示例11: GetHtml

        /// <summary>
        /// The get html.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <param name="type">
        /// The type.
        /// </param>
        public static void GetHtml(int id, ResultType type)
        {
            var wc = new WebClient();
            var url1 = Utils.GetWebSiteUrl;
            var url2 = url1;
            switch (type)
            {
                case ResultType.Product:
                    url1 += "/Product/item/" + id;
                    url2 += "/Product/item-id-" + id + ".htm";
                    break;
                case ResultType.Team:
                    url1 += "/Home/TuanItem/" + id;
                    url2 += "/Home/TuanItem/" + id + ".htm";
                    break;
                case ResultType.LP:
                    url1 += "/LandingPage/" + id;
                    url2 += "/LandingPage/" + id + ".htm";
                    break;
                case ResultType.Acticle:
                    url1 += "/Acticle/" + id;
                    url2 += "/Acticle/" + id + ".htm";
                    break;
                case ResultType.Help:
                    url1 += "/Help/" + id;
                    url2 += "/Help/" + id + ".htm";
                    break;
            }

            wc.DownloadString(url1);
            wc.DownloadString(url2);
        }
开发者ID:jxzly229190,项目名称:OnlineStore,代码行数:41,代码来源:HttpRequest.cs

示例12: GetBlogs

        public List<Blog> GetBlogs()
        {
            var token = GetToken();
            var url = GetReposUrl();

            var uriBuilder = new UriBuilder(url);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);

            query["access_token"] = token;
            uriBuilder.Query = query.ToString();

            var client = new WebClient();
            client.Headers.Add("user-agent", "Engineer In Dev");

            // Get the directories within the Repos directory of the project
            var content = Json.Decode(client.DownloadString(uriBuilder.ToString()));

            // Iterate over each directory
            for (var i = 0; i < content.Length; i++)
            {
                var tempBuilder = uriBuilder;
                tempBuilder.
                tempBuilder.Fragment = content[i]["name"];
                var blogs = Json.Decode(client.DownloadString(tempBuilder.ToString()));
            }

            return new List<Blog>();
        }
开发者ID:MatthewHartz,项目名称:EngineerInDev,代码行数:28,代码来源:GithubAccessHelper.cs

示例13: GetstringIpAddress

        //strIP为IP
        /// <summary>  
        /// 根据IP 获取物理地址  
        /// </summary>  
        /// <param name="strIP"></param>  
        /// <returns></returns>  
        public static string GetstringIpAddress(string strIP)
        {
            string m_IpAddress = strIP.Trim();

            //string[] ip = ipAddress.Split('.');
               // ipAddress = ip[0] + "." + ip[1] + ".1.1";

            WebClient client = new WebClient();
            client.Encoding = System.Text.Encoding.GetEncoding("GB2312");
            string html;
            try
            {
                html = client.DownloadString("http://www.ip138.com/ips1388.asp?ip=" + m_IpAddress + "&action=2");

            }
            catch (Exception ex)
            {
                html = client.DownloadString("http://www.ip138.com/ips1388.asp?ip=" + m_IpAddress + "&action=2");
            }

            string p = @"<li>本站主数据:(?<location>[^<>]+?)</li>";

            Match match = Regex.Match(html, p);
            string m_Location = match.Groups["location"].Value.Trim();
            int index = m_Location.IndexOf(" ");
            if (index != -1)
            {
                m_Location = m_Location.Substring(0, index);
            }
            return m_Location;
        }
开发者ID:shenruizong,项目名称:PingTest,代码行数:37,代码来源:AddIpWindow.xaml.cs

示例14: addInventories

        private void addInventories()
        {
            WebClient webClient = new WebClient();
            webClient.Encoding = System.Text.Encoding.UTF8;
            JArray characters = JArray.Parse(webClient.DownloadString("https://api.guildwars2.com/v2/characters?access_token=" + apiKey));

            foreach (String character in characters)
            {
                RootObject inventory = JsonConvert.DeserializeObject<RootObject>(webClient.DownloadString("https://api.guildwars2.com/v2/characters/" + character + "?access_token=" + apiKey));
                foreach (Bag bag in inventory.bags)
                {
                    if (bag != null)
                    {
                        foreach (Item item in bag.inventory)
                        {
                            try
                            {
                                ids.Add(new ListItem(item.id.ToString(), item.count, character));
                            }
                            catch { }
                        }
                    }
                }
            }
        }
开发者ID:ErinvanderVeen,项目名称:GW2-Inv-search,代码行数:25,代码来源:Form1.cs

示例15: LoadButton_Click

        private void LoadButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                using (var webClient = new WebClient())
                {
                    string xhtml = webClient.DownloadString("http://www.milovana.com/webteases/showflash.php?id=" + TeaseIdTextBox.Text);

                    var match = Regex.Match(xhtml, @"<div id=""headerbar"">\s*<div class=""title"">(?<title>.*?) by <a href=""webteases/#author=(?<authorid>\d+)"" [^>]*>(?<authorname>.*?)</a></div>", RegexOptions.Multiline | RegexOptions.Singleline);

                    TeaseTitleTextBox.Text = match.Groups["title"].Value;
                    AuthorNameTextBox.Text = match.Groups["authorname"].Value;
                    AuthorIdTextBox.Text = match.Groups["authorid"].Value;

                    string[] scriptLines = webClient.DownloadString("http://www.milovana.com/webteases/getscript.php?id=" + TeaseIdTextBox.Text).Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

                    SelectedTease = new FlashTeaseConverter().Convert(TeaseIdTextBox.Text, TeaseTitleTextBox.Text, AuthorIdTextBox.Text, AuthorNameTextBox.Text, scriptLines);

                    ConverionErrorTextBox.Visible = SelectedTease.Pages.Exists(page => !String.IsNullOrEmpty(page.Errors));

                    Cursor = Cursors.Default;
                }
            }
            catch (Exception err)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(err.Message, "Error while downloading tease", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
开发者ID:d3vi0n,项目名称:TeaseMe,代码行数:30,代码来源:OpenForm.cs


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