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


C# StreamReader.ReadToEndAsync方法代码示例

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


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

示例1: GetWeather

		/// <summary>
		/// Performs web request and gets the weather from the service.
		/// </summary>
		/// <returns>The weather.</returns>
		/// <param name="location">Location to get the weather</param>
		public static async Task<WeatherData> GetWeather(Location location)
		{
			WeatherData result = null;
			string weatherUrl = string.Format (WEATHER_URL, EnumHelper.GetDescription (Subscription.Subscript.free), location.city, NUMBER_OF_DAYS.ToString (), ApplicationSettingsHelper.API_KEY);
			HttpWebRequest request = (HttpWebRequest)WebRequest.Create(weatherUrl);

			using(WebResponse response = await request.GetResponseAsync())
			{
				using (Stream resStream = response.GetResponseStream ()) 
				{
					using (StreamReader reader = new StreamReader (resStream)) 
					{
						string jsonResult = await reader.ReadToEndAsync ();
						result = JsonConvert.DeserializeObject<WeatherData> (jsonResult);
					}
				}
			}
			 
			int  length1 = result.data.weather.Length;
			int  length2 = result.data.weather[0].hourly.Length;

			// TODO: investigate ho w to run this tasks in Parallel
			for( int i = 0; i < length1; i++){
				for(int j = 0; j < length2; j++) {
					//taskArray[i*length2 + j]  = Task.Factory.StartNew(async () => { await GetWeatherImageFile (result.data.weather[i].hourly[j].weatherIconUrl[0].value); });
					await GetWeatherImageFile (result.data.weather[i].hourly[j].weatherIconUrl[0].value);
				}
			}
			return result;
		}
开发者ID:dorofeev-serdg,项目名称:Xamarin,代码行数:35,代码来源:WeatherClient.cs

示例2: Invoke

        public async Task Invoke(HttpContext context)
        {
            using (var memoryStream = new MemoryStream())
            {
                var bodyStream = context.Response.Body;
                context.Response.Body = memoryStream;

                await _next(context);

                var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
                if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
                {
                    {
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        using (var streamReader = new StreamReader(memoryStream))
                        {
                            string body = await streamReader.ReadToEndAsync();
                            body = MinifyHtml(body);
                            using (var minBodyStream = new MemoryStream())
                            using (var streamWriter = new StreamWriter(minBodyStream))
                            {
                                streamWriter.Write(body);
                                streamWriter.Flush();
                                minBodyStream.Seek(0, SeekOrigin.Begin);
                                await minBodyStream.CopyToAsync(bodyStream);
                            }
                        }
                    }
                }
            }
        }
开发者ID:okusnadi,项目名称:HtmlMinifier,代码行数:31,代码来源:HtmlMinifierMiddleWare.cs

示例3: GetPageText

        private async Task<string> GetPageText(string page)
        {
            string result = "";
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(page);
                using (WebResponse response = await request.GetResponseAsync().ConfigureAwait(false))
                {

                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        result = await stream.ReadToEndAsync().ConfigureAwait(false);
                        return result;
                    }
                }
            }
            catch (WebException)
            {
                return "";
            }
            catch (UriFormatException)
            {
                return "";
            }
        }
开发者ID:RomanBodnar,项目名称:SitemapGenerator,代码行数:25,代码来源:Crawler.cs

示例4: With_WebSocket_CanReadTwoBufferedSmallFrames

        public void With_WebSocket_CanReadTwoBufferedSmallFrames()
        {
            var handshake = GenerateSimpleHandshake();
            using (var ms = new MemoryStream())
            using (WebSocket ws = new WebSocketRfc6455(ms, new WebSocketListenerOptions() { PingTimeout = Timeout.InfiniteTimeSpan }, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1), new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2), handshake.Request, handshake.Response, handshake.NegotiatedMessageExtensions))
            {
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Write(new Byte[] { 129, 130, 75, 91, 80, 26, 3, 50 }, 0, 8);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                var reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEnd();
                    Assert.AreEqual("Hi", s);
                }

                reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNotNull(reader);
                using (var sr = new StreamReader(reader, Encoding.UTF8, true, 1024, true))
                {
                    String s = sr.ReadToEndAsync().Result;
                    Assert.AreEqual("Hi", s);
                }

                reader = ws.ReadMessageAsync(CancellationToken.None).Result;
                Assert.IsNull(reader);
            }
        }
开发者ID:Stoom,项目名称:WebSocketListener,代码行数:31,代码来源:With_WebSocket.cs

示例5: RedeemRefreshTokenInternalAsync

        private static async Task<TokenResponse> RedeemRefreshTokenInternalAsync(OAuthAccount account)
        {
            HttpWebRequest request = WebRequest.CreateHttp(account.TokenService);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            var requestStream = await request.GetRequestStreamAsync();
            var writer = new StreamWriter(requestStream);

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("client_id={0}", Uri.EscapeDataString(account.ClientId));
            sb.AppendFormat("&redirect_uri={0}", Uri.EscapeDataString(account.RedirectUri));
            sb.AppendFormat("&client_secret={0}", Uri.EscapeDataString(account.ClientSecret));
            sb.AppendFormat("&refresh_token={0}", Uri.EscapeDataString(account.RefreshToken));
            sb.Append("&grant_type=refresh_token");
            if (null != account.Resource)
                sb.AppendFormat("&resource={0}", Uri.EscapeDataString(account.Resource));

            var content = sb.ToString();
            await writer.WriteAsync(content);
            await writer.FlushAsync();

            var response = await request.GetResponseAsync() as HttpWebResponse;
            if (null != response && response.StatusCode == HttpStatusCode.OK)
            {
                var responseStream = response.GetResponseStream();
                if (null != responseStream)
                {
                    var reader = new StreamReader(responseStream);
                    return JsonConvert.DeserializeObject<TokenResponse>(await reader.ReadToEndAsync());
                }
            }
            return null;
        }
开发者ID:ahaadi,项目名称:markdown-scanner,代码行数:34,代码来源:OAuthTokenGenerator.cs

示例6: ResponseLimit

        public async Task ResponseLimit()
        {
            var client = CreateClient();
            var url = BaseUrl + "/000/" + Guid.NewGuid().ToString();

            var request = new HttpRequestMessage(HttpMethod.Post, url + "/xhr_streaming");
            var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

            string msg = "\"" + new string('x', 128) + "\"";
            int nrOfMessages = 31;
            for (int i = 0; i < nrOfMessages; i++)
            {
                var sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[" + msg + "]", Encoding.UTF8, "application/json"));
                Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);
            }

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var contentStream = await response.Content.ReadAsStreamAsync();
            var reader = new StreamReader(contentStream);
            var prelude = await reader.ReadLineAsync();
            var open = await reader.ReadLineAsync();
            Assert.Equal(new string('h', 2048), prelude);
            Assert.Equal("o", open);
            var remaining = await reader.ReadToEndAsync();
            Assert.Equal(string.Concat(Enumerable.Repeat("a[" + msg + "]\n", nrOfMessages)), remaining);
        }
开发者ID:tmds,项目名称:Tmds.SockJS,代码行数:26,代码来源:XhrStreamingTest.cs

示例7: LoadByKeyAsync

        public async Task<string> LoadByKeyAsync(string key)
        {
            using (await _asyncLock.LockAsync())
            {
                var fileName = "cache_" + key;

                var existsFile = await ApplicationData.Current.LocalCacheFolder.TryGetItemAsync(fileName);

                //var existsFile = await FileSystem.Current.LocalStorage.CheckExistsAsync(fileName);

                if (existsFile != null)
                {
                    using (var stream = (await ((StorageFile)existsFile).OpenStreamForReadAsync()))
                    {
                        using (var dataReader = new StreamReader(stream, Encoding.UTF8))
                        {
                            var res = await dataReader.ReadToEndAsync();

                            return res;
                        }
                    }
                }

                return null;
            }
        }
开发者ID:bondarenkod,项目名称:Eve,代码行数:26,代码来源:LocalCacheService.cs

示例8: GetProvByPhoneNum

        /// <summary>
        /// 根据手机号码获取号码属地
        /// </summary>
        /// <param name="_PhoneNum"></param>
        /// <returns></returns>
        public async Task<PhoneSearchGetBak> GetProvByPhoneNum(string _PhoneNum)
        {
            if (string.IsNullOrWhiteSpace(_PhoneNum))
                return null;
            string _url = "http://shop.10086.cn/i/v1/res/numarea/" + _PhoneNum;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_url);
                request.Method = "GET";
                request.KeepAlive = true;

                request.CookieContainer = new CookieContainer();

                using (HttpWebResponse mResponse = (HttpWebResponse)request.GetResponse())
                {
                    cookie = request.CookieContainer;//如果用不到Cookie,删去即可  

                    using (Stream mStream = mResponse.GetResponseStream())
                    {
                        using (StreamReader myStreamReader =
                            new StreamReader(mStream, Encoding.GetEncoding("utf-8")))
                        {
                            string retString = await myStreamReader.ReadToEndAsync();
                            return JsonConvert.DeserializeObject<PhoneSearchGetBak>(retString);
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
            return null;
        }
开发者ID:MaricoShi,项目名称:SeekAsk,代码行数:40,代码来源:PhoneUtil2.cs

示例9: GoGoGo

        private async Task GoGoGo()
        {
            var webRequest = WebRequest.Create(GetUrl());
            //获取或设置用于对 Internet 资源请求进行身份验证的网络凭据
            webRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("该请求的协议方法:{0}\n", webRequest.Method);
            sb.AppendFormat("访问Internet的网络代理:{0}\n", webRequest.Proxy);
            sb.AppendFormat("请求数据的内容长度:{0}\n", webRequest.ContentLength);
            sb.AppendFormat("与该请求关联的URI:{0}\n", webRequest.RequestUri);
            sb.AppendFormat("获取或设置请求超时之前的时间(毫秒):{0}\n", webRequest.Timeout);

            //客户端不应该创建Response,而是通过WebRequest的GetResponse方法进行创建
            var webResponse = await webRequest.GetResponseAsync();

            sb.AppendFormat("响应请求的URI:{0}\n", webResponse.ResponseUri);

            //获取返回数据流
            using (var stream = webResponse.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    sb.AppendLine(await reader.ReadToEndAsync());
                }
            }
            rtxt1.Text = sb.ToString();
        }
开发者ID:Feng2012,项目名称:LoTCodeBase,代码行数:27,代码来源:Form1.cs

示例10: Create

        private async Task<string> Create()
        {
            string sql;
            var assembly = typeof(TestDatabase).GetTypeInfo().Assembly;
            using (var reader = new StreamReader(assembly.GetManifestResourceStream(_sqlFile)))
            {
                sql = await reader.ReadToEndAsync();
            }

            var dbName = await CreateDatabase();
            var connectionString = $"Server=localhost;Port=5432;Database={_databaseName};User Id=postgres;Password=s1mpl3;";

            using (var connection = new NpgsqlConnection(connectionString))
            {
                await connection.OpenAsync();

                using (var command = connection.CreateCommand())
                {
                    foreach (
                        var statement in
                        Regex.Split(sql, @"^\s*GO\s*$", RegexOptions.Multiline)
                            .Where(s => !string.IsNullOrWhiteSpace(s)))
                    {
                        //_logger.LogDebug(sql);
                        command.CommandText = statement;
                        await command.ExecuteNonQueryAsync();
                    }
                }
            }
            return _connectionString = connectionString;
        }
开发者ID:RendleLabs,项目名称:Simple.Data.Core,代码行数:31,代码来源:TestDatabase.cs

示例11: SendRequest

    private async void SendRequest()
    {
      try
      {
        using (ISitecoreWebApiSession session = this.instanceSettings.GetSession())
        {
          var request = ItemWebApiRequestBuilder.RenderingHtmlRequestWithSourceAndRenderingId(sourceIdTextField.Text, renderingIdTextField.Text)
            .Build();

          this.ShowLoader();

          Stream response = await session.ReadRenderingHtmlAsync(request);

          response.Position = 0;
          string htmlText = "";
          using (StreamReader reader = new StreamReader(response))
          {
            htmlText = await reader.ReadToEndAsync();
          }

          this.resultWebView.LoadHtmlString(htmlText, null);
        }
      }
      catch(Exception e) 
      {
        AlertHelper.ShowLocalizedAlertWithOkOption("Error", e.Message);
      }
      finally
      {
        BeginInvokeOnMainThread(delegate
        {
          this.HideLoader();
        });
      }
    }
开发者ID:amatkivskiy,项目名称:sitecore-xamarin-pcl-sdk,代码行数:35,代码来源:RenderingHtmlViewController.cs

示例12: LoadToken

        public async Task<AzureToken> LoadToken(string subscriptionId)
        {
            string path = Path.Combine(_root, "Subscriptions", subscriptionId + ".dat");
            if (!File.Exists(path))
            {
                return null;
            }

            string content = null;
            using (var reader = new StreamReader(path))
            {
                content = await reader.ReadToEndAsync();
            }
            if (content == null)
            {
                return null;
            }
            var unprotected =
                Encoding.UTF8.GetString(
                    ProtectedData.Unprotect(
                        Convert.FromBase64String(content),
                        null,
                        DataProtectionScope.CurrentUser));
            
            return JsonFormat.Deserialize<AzureToken>(unprotected);
        }
开发者ID:NuGet,项目名称:NuGet.Operations,代码行数:26,代码来源:AzureTokenManager.cs

示例13: WriteWebRequestSizeAsync

        private static async Task WriteWebRequestSizeAsync(
            string url)
        {
            try
            {
                WebRequest webRequest =
                    WebRequest.Create(url);

                WebResponse response =
                    await webRequest.GetResponseAsync();
                using(StreamReader reader =
                    new StreamReader(
                        response.GetResponseStream()))
                {
                    string text =
                        await reader.ReadToEndAsync();
                    Console.WriteLine(
                        FormatBytes(text.Length));
                }
            }
            catch(WebException)
            {
                // ...
            }
            catch(IOException)
            {
                // ...
            }
            catch(NotSupportedException)
            {
                // ...
            }
        }
开发者ID:rubycoder,项目名称:EssentialCSharp,代码行数:33,代码来源:Listing18.15.AsynchronousWebRequestUsingTaskAsynchronyPattern.cs

示例14: SendRequestXmlDocumentAsync

        /// <summary>
        /// Async method, return Response xmlDocument
        /// </summary>
        /// <param name="xmlRequest">xml request document</param>
        /// <returns></returns>
        public static async Task<XmlDocument> SendRequestXmlDocumentAsync(XmlDocument xmlRequest)
        {

            var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.novaposhta.ua/v2.0/xml/");
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.ContentType = @"application/x-www-form-urlencoded";
            ServicePointManager.DefaultConnectionLimit = 2000;
         
            var streamOut = new StreamWriter(await httpWebRequest.GetRequestStreamAsync());
            await streamOut.WriteAsync(xmlRequest.InnerXml);

            //streamOut.Flush();
            streamOut.Close();

            //In Stream
            var response = (await httpWebRequest.GetResponseAsync()).GetResponseStream();

            if (response == null)
                return null;

            var streamIn = new StreamReader(response);

            string strResponse = await streamIn.ReadToEndAsync();
            streamIn.Close();
            response.Close();

            //Load XML data to XmlDocument
            var xmlResponse = new XmlDocument();
            xmlResponse.LoadXml(strResponse);

            return xmlResponse;
        }
开发者ID:IhorHolovatsky,项目名称:NovaPoshta_API,代码行数:38,代码来源:APImethods.cs

示例15: TimerCallback

        private async void TimerCallback(object state)
        {
            try
            {
                using (var stream = await _httpClient.Get(new HttpRequestOptions
                {
                    Url = "http://bot.whatismyipaddress.com/"

                }).ConfigureAwait(false))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        var address = await reader.ReadToEndAsync().ConfigureAwait(false);

                        if (IsValid(address))
                        {
                            ((ConnectManager) _connectManager).OnWanAddressResolved(address);
                            CacheAddress(address);
                        }
                    }
                }
            }
            catch
            {
            }
        }
开发者ID:Ceten,项目名称:MediaBrowser,代码行数:26,代码来源:ConnectEntryPoint.cs


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