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


C# WebClient类代码示例

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


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

示例1: SendGETRequest

 private void SendGETRequest(string url)
 {
     using (WebClient wc = new WebClient())
     {
         wc.DownloadStringAsync(new Uri(url));
     }
 }
开发者ID:nburns,项目名称:main_trunk,代码行数:7,代码来源:NetworkInterface.cs

示例2: RetrieveScript

    /// <summary>
    /// Retrieves the specified remote script using a WebClient.
    /// </summary>
    /// <param name="file">The remote URL</param>
    private static string RetrieveScript(string file)
    {
        string script = null;

        try
        {
            Uri url = new Uri(file, UriKind.Absolute);

            using (WebClient client = new WebClient())
            using (Stream buffer = client.OpenRead(url))
            using (StreamReader reader = new StreamReader(buffer))
            {
                script = StripWhitespace(reader.ReadToEnd());
                HttpContext.Current.Cache.Insert(file, script, null, Cache.NoAbsoluteExpiration, new TimeSpan(7, 0, 0, 0));
            }
        }
        catch (System.Net.Sockets.SocketException)
        {
            // The remote site is currently down. Try again next time.
        }
        catch (UriFormatException)
        {
            // Only valid absolute URLs are accepted
        }

        return script;
    }
开发者ID:giangcoffee,项目名称:cafef.redis,代码行数:31,代码来源:CompressWebResource.cs

示例3: Main

    static void Main()
    {
        Console.WriteLine(@"Problem 4. Download file
Write a program that downloads a file from Internet (e.g. Ninja image) 
and stores it the current directory.
Find in Google how to download files in C#.
Be sure to catch all exceptions and to free any used resources in the 
finally block.
============================================================================
Solution:");
        string sourceResource = "http://blogs.telerik.com/images/default-source/miroslav-miroslav/super_ninja.png?sfvrsn=2";
        string localFileName = Path.GetFileName(sourceResource);
        using (WebClient myWebClient = new WebClient())
        {
            try
            {
                Console.WriteLine("Start downloading {0}", sourceResource);
                myWebClient.DownloadFile(sourceResource, localFileName);
                Console.WriteLine("Download succesfull.");
                Console.WriteLine("You can see downloaded file in: local folder of this program\\bin\\Debug\\");
            }
            catch (WebException ex)
            {
                Console.Write(ex.Message);
                if (ex.InnerException != null)
                    Console.WriteLine(" " + ex.InnerException.Message);
                else
                    Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Something going wrong. Details: " + ex.Message);
            }
        }
    }
开发者ID:LafForce,项目名称:TelerikAcademyHWs,代码行数:35,代码来源:DlFile.cs

示例4: Main

 static void Main()
 {
     WebClient webClient = new WebClient();
     try
     {
         webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"C:\Users\Konstantin Iliev\Documents\txt.txt");
     }
     catch (ArgumentException ae)
     {
         Console.WriteLine("{0} - {1}", ae.GetType(), ae.Message);
     }
     catch (WebException webEx)
     {
         Console.WriteLine("{0} - {1}", webEx.GetType(), webEx.Message);
         Console.WriteLine("Destination not found!");
     }
     catch (NotSupportedException supportEx)
     {
         Console.WriteLine("{0} - {1}", supportEx.GetType(), supportEx.Message);
         Console.WriteLine(supportEx.Message);
     }
     catch (Exception allExp)
     {
         Console.WriteLine("{0} - {1}", allExp.GetType(), allExp.Message);
     }
 }
开发者ID:K-Iliev,项目名称:C-Sharp-Part-Two,代码行数:26,代码来源:DownloadFile.cs

示例5: 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

示例6: SendSms

    public string SendSms(List<string> mobiles)
    {
        using (var client = new WebClient())
        {
            try
            {
                string langCode = "1";
                if (Regex.IsMatch(Message, @"\p{IsArabic}+"))
                {
                    langCode = "2";
                }

                client.Headers.Add("content-type", "text/plain");
                string mobile=String.Join(",",mobiles.ToArray());
                string result = client.DownloadString(String.Format("http://brazilboxtech.com/api/send.aspx?username=smartksa&password=ksasmrt95647&language={0}&sender=NCSS&mobile={1}&message={2}",langCode, mobile, Message));
                if (result.StartsWith("OK"))
                {
                    return String.Empty;
                }
                return result;
            }
            catch (Exception ex)
            {

                return ex.Message;
            }

        }
    }
开发者ID:samercs,项目名称:NCSS,代码行数:29,代码来源:SMSSender.cs

示例7: Main

    static void Main(string[] args)
    {
        /*     Write a program that downloads a file from Internet (e.g. Ninja image) and stores it in the current directory.
                   Find in Google how to download files in C#.
                   Be sure to catch all exceptions and to free any used resources in the finally block.*/

            Console.WriteLine("Enter Internet file address: "); // https://telerikacademy.com/Content/Images/news-img01.png
            string internetAddress = Console.ReadLine();
            string extension = internetAddress.Substring(internetAddress.LastIndexOf('.'), internetAddress.Length - internetAddress.LastIndexOf('.'));

            using (WebClient internetRover = new WebClient())
            {
                try
                {
                    Console.WriteLine("Recieving data...");
                    internetRover.DownloadFile(internetAddress, "downloadedFile" + extension);
                    Console.WriteLine("File successfully downloaded! File Location:...\\bin\\Debug");
                }
                catch (ArgumentNullException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (WebException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (NotSupportedException ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }
    }
开发者ID:Boyan1912,项目名称:C-Sharp-Part-2,代码行数:33,代码来源:Program.cs

示例8: Main

    static void Main()
    {
        WebClient webClient = new WebClient();
            using (webClient)
            {
                try
                {
                    webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"..\..\Logo-BASD.jpg");
                    //this row will be executed only if downwoad is successfull
                    Console.WriteLine("The file is downloaded");
                }
                catch (ArgumentNullException ex1)
                {
                    Console.WriteLine("{0}",ex1.Message);
                }
                catch (System.Net.WebException ex2)
                {
                    Console.WriteLine("{0}", ex2.Message);
                }
                catch (System.NotSupportedException ex3)
                {
                    Console.WriteLine("{0}", ex3.Message);
                }

            }
    }
开发者ID:kicata,项目名称:CSharpPartTwoNew,代码行数:26,代码来源:04+DownloadFileFromWeb.cs

示例9: Main

 static void Main()
 {
     Console.WriteLine("Enter URI(adress) from where you will download: ");
     string url = Console.ReadLine();
     Console.WriteLine("Enter name for your file: ");
     string fileName = Console.ReadLine();
     //using  closes the resource after it`s work is done
     using (WebClient webClient = new WebClient())
     {
         try
         {
             webClient.DownloadFile(url, fileName);
             Console.WriteLine("Download complete!");
         }
         catch (ArgumentNullException)
         {
             Console.WriteLine("Either adress parameter is null or filename parameter is null!");
         }
         catch (WebException)
         {
             Console.WriteLine("The URI adress is invalid,filename is null or empty or an error occurred while downloading data!");
         }
         catch (NotSupportedException)
         {
             Console.WriteLine("The method has been called simultaneously on multiple threads.");
         }
         catch (ArgumentException)
         {
             Console.WriteLine("The path is not of a legal form.");
         }
     }
 }
开发者ID:NK-Hertz,项目名称:Telerik-Academy-2014,代码行数:32,代码来源:Downloader.cs

示例10: method_0

 public void method_0()
 {
     try
     {
         string xml;
         using (WebClient webClient = new WebClient())
         {
             xml = webClient.DownloadString(this.string_1 + "/main.xml");
         }
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xml);
         XmlNodeList elementsByTagName = xmlDocument.GetElementsByTagName("repofile");
         XmlNodeList elementsByTagName2 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("information");
         foreach (XmlElement xmlElement in elementsByTagName2)
         {
             XmlNodeList elementsByTagName3 = xmlElement.GetElementsByTagName("id");
             XmlNodeList elementsByTagName4 = xmlElement.GetElementsByTagName("name");
             this.string_0 = elementsByTagName4[0].InnerText;
             this.string_2 = elementsByTagName3[0].InnerText;
         }
         XmlNodeList elementsByTagName5 = ((XmlElement)elementsByTagName[0]).GetElementsByTagName("category");
         foreach (XmlElement xmlElement2 in elementsByTagName5)
         {
             XmlNodeList elementsByTagName3 = xmlElement2.GetElementsByTagName("id");
             XmlNodeList elementsByTagName4 = xmlElement2.GetElementsByTagName("name");
             GClass2 gClass = new GClass2();
             gClass.string_1 = elementsByTagName4[0].InnerText;
             gClass.string_0 = elementsByTagName3[0].InnerText;
         }
     }
     catch
     {
     }
 }
开发者ID:ZelkovaHabbo,项目名称:NF3_Compilable,代码行数:34,代码来源:GClass0.cs

示例11: Main

 static void Main()
 {
     string decorationLine = new string('-', 80);
     Console.Write(decorationLine);
     Console.WriteLine("***Downloading a file from Internet and storing it in the current directory***");
     Console.Write(decorationLine);
     WebClient webClient = new WebClient();
     try
     {
         string remoteUri = "http://www.telerik.com/images/newsletters/academy/assets/";
         string fileName = "ninja-top.gif";
         string fullFilePathOnWeb = remoteUri + fileName;
         webClient.DownloadFile(fullFilePathOnWeb, fileName);
         Console.WriteLine("Downloading '{0}' from {1} is completed!", fileName, remoteUri);
         Console.WriteLine("You can find it in {0}.", Environment.CurrentDirectory);
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("No file address is given!");
     }
     catch (WebException webException)
     {
         Console.WriteLine(webException.Message);
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("Downloading a file is in process! Cannot download multiple \nfiles simultaneously!");
     }
     finally
     {
         webClient.Dispose();
     }
 }
开发者ID:vladislav-karamfilov,项目名称:TelerikAcademy,代码行数:33,代码来源:DownloadingFile.cs

示例12: Main

    static void Main()
    {
        try
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"C:\");
        }

        catch (ArgumentNullException)
        {
            Console.WriteLine("The address parameter is null.");
        }

        catch (WebException)
        {
            Console.Write("The URI formed by combining BaseAddress and address is invalid");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(" or ");
            Console.ResetColor();
            Console.Write("filename is null or Empty");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(" or ");
            Console.ResetColor();
            Console.Write("the file does not exist");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write(" or ");
            Console.ResetColor();
            Console.WriteLine("an error occurred while downloading data.");
        }

        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple threads.");
        }
    }
开发者ID:Nikolay-D,项目名称:TelerikSchoolAcademy,代码行数:35,代码来源:DownloadFromNetwork.cs

示例13: Main

    static void Main()
    {
        using (WebClient webClient = new WebClient())
        {
            try
            {
                Console.WriteLine("Starting to download...");
                webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "../../Logo-BASD.jpg");
                Console.WriteLine("Downloaded!");
            }

            catch (WebException ex)
            {
                Console.Error.WriteLine("Sorry, there was an error!" + ex.Message);
            }
            catch (ArgumentNullException ex)
            {
                Console.Error.WriteLine("Sorry, you didn't enter anything!" + ex.Message);
            }
            catch (NotSupportedException ex )
            {
                Console.Error.WriteLine("Sorry, there was an error!" + ex.Message);
            }
        }
    }
开发者ID:velinkoychev,项目名称:Shared,代码行数:25,代码来源:4.DownloadFile.cs

示例14: Main

 static void Main()
 {
     try
     {
         WebClient webClient = new WebClient();
         webClient.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", "news-img01.png");
         Console.WriteLine("You can find the downloaded image in 'bin' directory of the project.");
     }
     catch (ArgumentException ex)
     {
         Console.WriteLine(ex.Message);
     }
     catch (WebException ex)
     {
         Console.WriteLine(ex.Message);
     }
     catch (NotSupportedException ex)
     {
         Console.WriteLine(ex.Message);
     }
     catch (UnauthorizedAccessException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
开发者ID:DareDev1l,项目名称:TelerikAcademy,代码行数:25,代码来源:DownloadFile.cs

示例15: Main

    // Write a program that downloads a file from Internet
    // (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and
    // stores it the current directory. Find in Google how 
    // to download files in C#. Be sure to catch all exceptions
    // and to free any used resources in the finally block.

    static void Main()
    {
        WebClient client = new WebClient();
        using (client)
        {
            try
            {
                client.DownloadFile("http://academy.telerik.com/images/default-album/telerik-academy-banner-300x250.jpg?sfvrsn=2",
                            "../../../telerik-academy-banner-300x250.jpg");
            }
            catch (WebException we)
            {
                Console.Error.WriteLine("File is inaccessible!" + we.Message);
            }

            catch (NotSupportedException ne)
            {
                Console.Error.WriteLine("Ooops something went wrong!" + ne.Message);
            }
            catch (ArgumentNullException ae)
            {
                Console.Error.WriteLine("Ooops something went wrong!" + ae.Message);
            }
        }
    }
开发者ID:niki-funky,项目名称:Telerik_Academy,代码行数:31,代码来源:04.LoadPictureFromInternet.cs


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