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


C# WebClient.DownloadData方法代码示例

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


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

示例1: recentList

    private static List<string> recentList()
    {
        WebClient c = new WebClient();
        c.Headers.Add(@"User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
        var Settings = ExtensionManager.GetSettings("AudioStream");

        var stream = Settings.GetSingleValue("HighStream");
        if (!stream.ToLower().StartsWith("http")) stream = @"http://"+stream;
        if (!stream.EndsWith("/")) stream += "/";
        var a = c.DownloadData(stream+"played.html");

        var s = Encoding.GetEncoding(1252).GetString(a);
        var stringa = new string[] { @"<br><table border=0 cellpadding=2 cellspacing=2><tr><td>Played @</td><td><b>Song Title</b></td></tr><tr>" };

        var stuff = s.Split(stringa, StringSplitOptions.RemoveEmptyEntries)[1];
        var aftertd = stuff.Split(new string[] { @"</td><td>" }, StringSplitOptions.RemoveEmptyEntries);

        var lijstje = new List<string>();
        var nowplaying = aftertd[1].Split(new String[] { @"<td><b" }, StringSplitOptions.RemoveEmptyEntries)[0];
        lijstje.Add(nowplaying);
        for (int i = 2; i < aftertd.Length; i++)
        {
            lijstje.Add(aftertd[i].Split(new string[] { @"</tr>" }, StringSplitOptions.RemoveEmptyEntries)[0]);
        }
        return lijstje;
    }
开发者ID:nicknijenhuis,项目名称:Carnaval-Radio,代码行数:26,代码来源:RecentSongsService.cs

示例2: GetAuthorizationUrl

    /// <summary>
    /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    protected override string GetAuthorizationUrl(String callbackUrl)
    {
        OAuthBase auth = new OAuthBase();
        String requestUrl = provider.Host + provider.RequestTokenUrl;
        Uri url = new Uri(requestUrl);
        String requestParams = "";
        String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
            auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
            new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
        requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
        WebClient webClient = new WebClient();
        byte[] response;
        if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
        {
            response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
        }
        else
        {
            response = webClient.DownloadData(url + "?" + requestParams);
        }
        Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
        String requestToken = m.Groups[1].Value;
        String requestTokenSecret = m.Groups[2].Value;
        // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
        // just stick it in the session for now
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;

        return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
    }
开发者ID:ssommerfeldt,项目名称:TAC_EAB,代码行数:35,代码来源:OAuth1AuthorizationServiceViewController.cs

示例3: GetFromUser

    /// <summary>
    /// Get a list of newest YouTube videos for a given user.
    /// </summary>
    /// <param name="username">Username to get videos from.</param>
    /// <param name="includeDescription">Whether or not to include description. Warning: This requires an extra request to YouTube pr. video!</param>
    /// <returns>A list of YouTube videos.</returns>
    public static List<YouTubeVideo> GetFromUser(string username, bool includeDescription = false)
    {
        var url = string.Format("https://www.youtube.com/user/{0}/videos", username);
        var list = new List<YouTubeVideo>();
        var webClient = new WebClient();
        var source = string.Empty;

        try {
            var bytes = webClient.DownloadData(url);
            source = Encoding.UTF8.GetString(bytes);
        }
        catch { }

        if (string.IsNullOrEmpty(source))
            return list;

        var sp = source.IndexOf("/watch?v=", StringComparison.InvariantCultureIgnoreCase);

        while (sp > -1) {
            var video = parseSource(ref list, ref source, sp);

            if (video != null) {
                if (includeDescription)
                    getVideoDescription(ref video);

                list.Add(video);
            }

            source = source.Substring(sp + 3000);
            sp = source.IndexOf("/watch?v=", StringComparison.InvariantCultureIgnoreCase);
        }

        return list;
    }
开发者ID:nagilum,项目名称:YouTubeUserVideosParser,代码行数:40,代码来源:YouTubeUserVideos.cs

示例4: DownloadData

 public static byte[] DownloadData(this Uri uri)
 {
     if (uri == null)
         return null;
     WebClient client = new WebClient();
     return client.DownloadData(uri);
 }
开发者ID:zhang-xiao-ming,项目名称:RestApiClient,代码行数:7,代码来源:UriExtensions.cs

示例5: OnPreRender

    protected override void OnPreRender(EventArgs e)
    {
        //throw new Exception(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]));
        Response.Clear();
        Response.ContentType = "image/jpeg";
        WebClient webclient = new WebClient();
        webclient.Headers.Clear();
        webclient.Headers.Add("Accept: image/jpeg, application/x-ms-application, image/gif, image/png, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
        //webclient.Headers.Add("Accept-Encoding: gzip, deflate");
        webclient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");

        byte[] data = webclient.DownloadData(DES.Decrypt(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]), shTwiX.shFunctions.key));
        do
        {
        } while (webclient.IsBusy);
        ImageConverter imageConverter = new System.Drawing.ImageConverter();
        try
        {
            System.Drawing.Image image = (System.Drawing.Image)imageConverter.ConvertFrom(data);
            image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch
        {
            Response.Write(data.Length.ToString() + "<br/>" + Request.QueryString[0]);
        }
    }
开发者ID:shaahin,项目名称:shTwiX,代码行数:26,代码来源:image.aspx.cs

示例6: ProcessRequest

 public void ProcessRequest(HttpContext context) {
     context.Response.ContentType = "application/json";
     using (WebClient client = new WebClient())  
     {
         client.Encoding = Encoding.UTF8;
         context.Response.BinaryWrite(client.DownloadData(context.Request.QueryString["url"]));
     }
 }
开发者ID:niki-funky,项目名称:Telerik_Academy,代码行数:8,代码来源:Handler1.ashx.cs

示例7: GetPictureWithBitmap

    public override TransitPicture GetPictureWithBitmap(int id)
    {
        string url = Request["Src"];

        if (string.IsNullOrEmpty(url))
        {
            throw new Exception("Invalid url.");
        }

        string key = string.Format("AccountFeedItemPicture:{0}", url.GetHashCode());
        TransitPicture result = (TransitPicture) Cache[key];

        if (result != null)
            return result;

        // fetch the image to get its size
        WebClient client = new WebClient();
        client.Headers["Accept"] = "*/*";
        client.Headers["User-Agent"] = SessionManager.GetCachedConfiguration("SnCore.Web.UserAgent", "SnCore/1.0");
        result = new TransitPicture();
        result.Name = url;

        try
        {
            byte[] data = client.DownloadData(url);

            if (data == null)
            {
                throw new Exception("Missing file data.");
            }

            result.Bitmap = new ThumbnailBitmap(new MemoryStream(data), new Size(0, 0), 
                ThumbnailBitmap.s_FullSize, ThumbnailBitmap.s_ThumbnailSize).Bitmap;

            string created = (string)client.ResponseHeaders["Created"];
            if (string.IsNullOrEmpty(created)) created = (string)client.ResponseHeaders["Date"];
            if (string.IsNullOrEmpty(created) || !DateTime.TryParse(created, out result.Created))
                result.Created = DateTime.Now;

            string modified = (string)client.ResponseHeaders["Modified"];
            if (string.IsNullOrEmpty(modified) || !DateTime.TryParse(modified, out result.Modified))
                result.Modified = DateTime.Now;
        }
        catch(Exception ex)
        {
            string message = string.Format("This image cannot be displayed.\n{0}\n{1}",
                ex.Message, url);
            result.Bitmap = ThumbnailBitmap.GetBitmapDataFromText(message, 8, 0, 0);
            result.Modified = result.Created = DateTime.Now;
        }

        Cache.Insert(key, result, null, Cache.NoAbsoluteExpiration,
            SessionManager.DefaultCacheTimeSpan);

        return result;
    }
开发者ID:dblock,项目名称:sncore,代码行数:56,代码来源:AccountFeedItemPicture.aspx.cs

示例8: DownloadAsBytesAsync

	/// <summary>
	/// Downloads a file as an array of bytes.
	/// </summary>
	/// <param name="address">File URL</param>
	/// <param name="cancellationToken">Optional cancellation token</param>
	public static Task<byte[]> DownloadAsBytesAsync(string address, CancellationToken cancellationToken = new CancellationToken())
	{
		return Task.Factory.StartNew(
			delegate
			{
				using (var webClient = new WebClient())
				{
					return webClient.DownloadData(address);
				}
			}, cancellationToken);
	}
开发者ID:Awesome-MQP,项目名称:Storybook,代码行数:16,代码来源:AsyncTools.cs

示例9: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        string strIcon = Request.QueryString["Icon"].ToString();

        //Get Icon from Centrify
        WebClient wc = new WebClient();
        wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
        wc.Headers.Add("Authorization", "Bearer " + Session["ASPXAUTH"].ToString());
        byte[] bytes = wc.DownloadData(Session["NewPodURL"].ToString() + strIcon);
        Response.ContentType = "image/jpg";
        Response.BinaryWrite(bytes);
    }
开发者ID:erajsiddiqui,项目名称:CentrifyAPIExamples_APIDemoWebsite,代码行数:12,代码来源:GetSecureImage.aspx.cs

示例10: DownloadAsBytesAsync

 public static Task<byte[]> DownloadAsBytesAsync(string address)
 {
     var task = new Task<byte[]>(
         () =>
         {
             using (var webClient = new WebClient())
             {
                 return webClient.DownloadData(address);
             }
         });
     task.Start(TaskScheduler.Default);
     return task;
 }
开发者ID:iamchenxin,项目名称:CShape6_Unity3D,代码行数:13,代码来源:AsyncTools.cs

示例11: GetLatestVersion

    public static int GetLatestVersion()
    {
        //let us screenscrape the Google Site.
        WebClient wc = new WebClient ();
        byte [] pageData = wc.DownloadData ("http://code.google.com/p/skimpt");
        string pageHtml = System.Text.Encoding.ASCII.GetString(pageData);

        string ver;
        ver = pageHtml.Substring (pageHtml.IndexOf ("!!ver:"));
        ver = ver.Substring (6);
        ver = ver.Remove(ver.IndexOf("!!"));
     
        return Convert.ToInt32(ver);
    }
开发者ID:vantruc,项目名称:skimpt,代码行数:14,代码来源:autoupdater.cs

示例12: Check_function_Fund_price

    public static string Check_function_Fund_price(string stock_idX)
    {
        string stock_id = stock_idX;

        // 下載 Yahoo 奇摩股市資料 (範例為 2317 鴻海)
        WebClient client = new WebClient();
        MemoryStream ms = new MemoryStream(client.DownloadData(
        "http://tw.money.yahoo.com/currency_foreign2bank?currency=USD" + stock_id + ""));

        //        MemoryStream ms = new MemoryStream(client.DownloadData(
        //"http://tw.stock.yahoo.com/q/q?s=" + stock_id + ""));

        // 使用預設編碼讀入 HTML
        HtmlDocument doc = new HtmlDocument();
        doc.Load(ms, Encoding.UTF8);
        HtmlDocument docStockContext = new HtmlDocument();
        // 裝載第一層查詢結果

        docStockContext.LoadHtml(doc.DocumentNode.SelectSingleNode(
        "/html[1]/body[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[2]/table[1]").InnerHtml);

        // 取得個股標頭
        HtmlNodeCollection nodeHeaders =
         docStockContext.DocumentNode.SelectNodes("./tr[1]/td");
        // 取得個股數值
        string[] values = docStockContext.DocumentNode.SelectSingleNode(
        "./tr[3]").InnerText.Trim().Split('\n');

        // 輸出資料

        string[] title ={ "金融機構", "現金賣出", "現金買進" };
        for (int i = 0; i <= values.Length - 2; i++)
        {
            //Response.Write("Header:" + title[i] + values[i].ToString().Replace("加到投資組合", "") + "<br>");
        }
        string[] abc ={ "", "","" };
        abc[0] = values[0].Trim();
        abc[1] = values[1].Trim(); //stock_price
        abc[2] = values[2].Trim();//stock_name

        //Double last_price = System.Convert.ToDouble(abc);

        doc = null;
        docStockContext = null;
        client = null;
        ms.Close();

        return abc[0] + "," + abc[1]+","+abc[2];
    }
开发者ID:hsiehoscar,项目名称:stock_new,代码行数:49,代码来源:Default2.aspx.cs

示例13: Main

 static void Main()
 {
     try
     {
         string path = @"C:\Documents and Settings\Rami\My Documents\Visual Studio 2010\Projects\ExceptionHandling\Zadacha13\bin\Debug\logo.jpg";
         WebClient client = new WebClient();
         BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create));
         using (client)
         {
             byte[] arr = client.DownloadData("http://www.devbg.org/img/Logo-BASD.jpg");
             using (writer)
             {
                 foreach (var item in arr)
                 {
                     writer.Write(item);
                 }
             }
         }
     }
     catch (WebException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (UriFormatException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FileLoadException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FileNotFoundException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FieldAccessException e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
开发者ID:RamiAmaire,项目名称:TelerikAcademy,代码行数:45,代码来源:DownloadingFileAndCatchingExc.cs

示例14: CheckConnect

 public static string CheckConnect()
 {
     string msg = "";
     WebClient client = new WebClient();
     byte[] datasize = null;
     try
     {
         datasize = client.DownloadData("http://www.google.com");
     }
     catch (Exception ex)
     {
     }
     if (datasize != null && datasize.Length > 0)
         msg = "Internet Connection Available.";
     else
         msg = "Internet Connection Not Available.";
     return msg;
 }
开发者ID:websnipe-abhik,项目名称:Subpoena,代码行数:18,代码来源:DbConnectionController.cs

示例15: lnkbtnBrocher_Click

    protected void lnkbtnBrocher_Click(object sender, EventArgs e)
    {
        // Response.ContentType = "Application/pdf";
        //  Response.TransmitFile("~/brocher/brocher.pdf");

        try
        {
            string pdfPath = Server.MapPath("~/brochure/brochure.pdf");
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(pdfPath);
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
开发者ID:Testegg,项目名称:SriBalaji,代码行数:19,代码来源:MasterPage.master.cs


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