本文整理汇总了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;
}
示例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);
}
}
}
}
}
}
示例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 "";
}
}
示例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);
}
}
示例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;
}
示例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);
}
示例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;
}
}
示例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;
}
示例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();
}
示例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;
}
示例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();
});
}
}
示例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);
}
示例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;
}
示例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
{
}
}