本文整理汇总了C#中System.IO.StreamReader.ReadLineAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.ReadLineAsync方法的具体用法?C# StreamReader.ReadLineAsync怎么用?C# StreamReader.ReadLineAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamReader
的用法示例。
在下文中一共展示了StreamReader.ReadLineAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: InitLoadSet
public static async void InitLoadSet() {
string fileContent;
Uri uri = new Uri("ms-appx:///Data/Sets.txt");
file = await StorageFile.GetFileFromApplicationUriAsync(uri);
StreamReader sRead = new StreamReader(await file.OpenStreamForReadAsync());
fileContent = await sRead.ReadLineAsync();
KeyValuePair<int, object> res = Type(fileContent);
ListWords currentListWords = new ListWords();
while (res.Key != -1)
{
if (res.Key == 0)
{
currentListWords.Name = (string)res.Value;
SetsNames.Add((string)res.Value);
}
if (res.Key == 1)
{
currentListWords.Add((Word)res.Value);
}
if (res.Key == 2)
{
SetsWords.Add(currentListWords.Name, currentListWords);
currentListWords = new ListWords();
}
fileContent = sRead.ReadLineAsync().Result;
res = Type(fileContent);
}
MainPage.CurrentListWords = SetsWords["None"];
sRead.Dispose();
}
示例3: Open_Stream_Click
private async void Open_Stream_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
string url = String.Format("https://api.particle.io/v1/devices/{0}/events/NeedCover?access_token={1}", PHOTON1DEVICEID, ACCESS_TOKEN);
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
int blankRead = 0;
while (blankRead <= 1)
{
// Event comes streaming in 3 lines. blank line,
// "event: NeedCover",
// then a json line that starts with "data:",
// If more than a couple blank lines in a row then we're done with the stream.
var str = await reader.ReadLineAsync();
if (string.IsNullOrEmpty(str))
{
++blankRead;
}
else if (str == "event: NeedCover")
{
blankRead = 0;
var data = await reader.ReadLineAsync();
var jsonData = JsonConvert.DeserializeObject<ParticleEvent>(data.Substring(data.IndexOf("data:") + 5));
streamResultTextBox.Text = jsonData.data;
}
}
}
}
(sender as Button).IsEnabled = true;
}
示例4: Transport
public async Task Transport()
{
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);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("UTF-8", response.Content.Headers.ContentType.CharSet);
Assert.Equal("application/javascript", response.Content.Headers.ContentType.MediaType);
AssertCors(response, null);
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 sendResponse = await client.PostAsync(url + "/xhr_send", new StringContent("[\"x\"]", Encoding.UTF8, "application/json"));
Assert.Equal(HttpStatusCode.NoContent, sendResponse.StatusCode);
var message = await reader.ReadLineAsync();
Assert.Equal("a[\"x\"]", message);
client.Dispose();
}
示例5: ClientWork
private async void ClientWork(object state)
{
int clientId = (int)state;
using (var channel = this.connection.ConnectChannel())
{
using (StreamWriter writer = new StreamWriter(channel))
{
using (StreamReader reader = new StreamReader(channel))
{
string request = string.Format("Hello from {0}", clientId);
string response;
await writer.WriteLineAsync(request);
await writer.FlushAsync();
response = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
response = await reader.ReadLineAsync();
await channel.StopSendingAsync();
await channel.FlushAsync();
if (reader.EndOfStream)
{
Console.WriteLine("Client feel right!");
}
}
}
}
if (Interlocked.Decrement(ref pendingCount) == 0)
{
lock (termLock)
{
Monitor.Pulse(termLock);
}
}
}
示例6: WorkAsync
private static async Task WorkAsync(Channel channel)
{
using (channel)
{
using (var reader = new StreamReader(channel))
{
using (var writer = new StreamWriter(channel))
{
string request = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
request = await reader.ReadLineAsync();
await writer.WriteLineAsync(request);
await writer.FlushAsync();
Console.WriteLine("Server waiting for close");
if (reader.EndOfStream)
{
Console.WriteLine("Server feel right!");
}
await channel.StopSendingAsync();
await channel.FlushAsync();
}
}
}
}
示例7: HandshakeConnection
public async Task<bool> HandshakeConnection(NetworkStream ClientStream)
{
StreamReader Reader = new StreamReader(ClientStream);
StreamWriter Writer = new StreamWriter(ClientStream);
TCPGetRequestHeader RequestHeader = new TCPGetRequestHeader();
string message = await Reader.ReadLineAsync();
while (message != Terminal)
{
this.ParseHeader(message, ref RequestHeader);
message = await Reader.ReadLineAsync();
}
string accept = this.AcceptKey(RequestHeader.SocketKey);
Writer.Write("HTTP/1.1 101 Switching Protocols\r\n");
Writer.Write("Upgrade: websocket\r\n");
Writer.Write("Connection: Upgrade\r\n");
Writer.Write("Sec-WebSocket-Accept: " + accept + "\r\n");
Writer.Write("\r\n");
Writer.Flush();
return true;
}
示例8: MainForm_Load
private async void MainForm_Load(object sender, EventArgs e)
{
#region 进度提示窗口设置
ProgressForm progressForm = new ProgressForm();
progressForm.Size = new Size(600, 80);
progressForm.StartPosition = FormStartPosition.Manual;
progressForm.Location = new Point(this.DesktopLocation.X + this.Width / 2 - progressForm.Size.Width / 2, this.DesktopLocation.Y + this.Height / 2 - progressForm.Size.Height / 2);
progressForm.FormBorderStyle = FormBorderStyle.FixedToolWindow;
progressForm.progress.Maximum = 100;
progressForm.progress.Minimum = 0;
progressForm.progress.Value = 0;
progressForm.Show(this);
this.Enabled = false;
#endregion
using (StreamReader reader = new StreamReader("TitleUrl.txt"))
{
while (!reader.EndOfStream)
{
string title = await reader.ReadLineAsync();
string url = await reader.ReadLineAsync();
try
{
titleURL.Add(title, url);
}
catch (Exception)
{
// 异常:
// T:System.ArgumentNullException:
// key 为 null。
//
// T:System.ArgumentException:
// System.Collections.Generic.Dictionary`2 中已存在具有相同键的元素。
}
//更新进度条
if (progressForm.progress.Value < 90)
{
progressForm.progress.Value++;
progressForm.Text = "正在加载离线数据:" + progressForm.progress.Value + "%";
}
}
}
progressForm.progress.Value = 100;
progressForm.Text = "任务进度:" + progressForm.progress.Value + "%";
progressForm.Close();
this.Enabled = true;
}
示例9: SplitAsync
/// <summary>
/// Splits the file into the specified number of files.
/// </summary>
/// <param name="filePath">The file to split.</param>
/// <param name="fileCount">The number of files to split the original file into.</param>
/// <returns>The list of file names generated by splitting the original file.</returns>
public async Task<List<string>> SplitAsync(string filePath, int fileCount)
{
List<string> filePaths = new List<string>();
//Load the existing file.
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
//Count the total number of lines in the original file.
int lineCount = 0;
while (!streamReader.EndOfStream)
{
++lineCount;
await streamReader.ReadLineAsync();
}
//Compute the number of lines per file.
int linesPerFile = lineCount / fileCount;
streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
//Generate each output file.
for(int i = 0; i < fileCount; i++)
{
string fileName = Helpers.GetSplitFileName(i);
filePaths.Add(fileName);
using (FileStream newFileStream = new FileStream(fileName, FileMode.Create))
{
using (StreamWriter streamWriter = new StreamWriter(newFileStream))
{
for (int linesInCurrentFile = 0;
linesInCurrentFile < linesPerFile ||
(i == fileCount - 1 && !streamReader.EndOfStream); //Write any remaining lines (due to rounding) to the last file.
linesInCurrentFile++)
{
string line = await streamReader.ReadLineAsync();
await streamWriter.WriteLineAsync(line);
}
}
}
}
}
}
return filePaths;
}
示例10: ServerStub
private async void ServerStub(TcpClient client)
{
string ipClient = client.Client.RemoteEndPoint.ToString();
Console.WriteLine("Подключился клиент: {0}", ipClient);
NetworkStream ns = client.GetStream();
StreamWriter sw = new StreamWriter(ns);
StreamReader sr = new StreamReader(ns);
try
{
string method = await sr.ReadLineAsync();
int arg1 = int.Parse(await sr.ReadLineAsync());
int arg2 = int.Parse(await sr.ReadLineAsync());
int res = 0;
switch (method)
{
case "+":
res = add(arg1, arg2);
break;
case "-":
res = sub(arg1, arg2);
break;
case "*":
res = mul(arg1, arg2);
break;
default:
throw new Exception("Неверный код функции");
}
sw.WriteLine(res);
Console.WriteLine("Клиент {0} присал сообщение: {1} {2} {3} | {4}", ipClient, method, arg1, arg2, res);
}
catch (Exception e)
{
Console.WriteLine("Ошибка при обработке пакета от клиента: {0}", ipClient);
System.Diagnostics.Debug.WriteLine(e.StackTrace);
}
finally
{
sw.Close();
sr.Close();
client.Close();
Console.WriteLine("Клиент отключился: {0}", ipClient);
}
}
示例11: HandleClient
protected override async Task HandleClient(TcpClient client) {
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream)) {
string line = await reader.ReadLineAsync().ConfigureAwait(false);
while (line != null) {
writer.WriteLine(line);
writer.Flush();
line = await reader.ReadLineAsync().ConfigureAwait(false);
}
}
}
示例12: RunAsync
/// <summary>
/// Runs the mapper task.
/// </summary>
public async Task RunAsync()
{
CloudBlockBlob blob = new CloudBlockBlob(new Uri(this.blobSas));
Console.WriteLine("Matches in blob: {0}/{1}", blob.Container.Name, blob.Name);
using (Stream memoryStream = new MemoryStream())
{
//Download the blob.
await blob.DownloadToStreamAsync(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
using (StreamReader streamReader = new StreamReader(memoryStream))
{
Regex regex = new Regex(this.configurationSettings.RegularExpression);
int lineCount = 0;
//Read the file content.
while (!streamReader.EndOfStream)
{
++lineCount;
string textLine = await streamReader.ReadLineAsync();
//If the line matches the search parameters, then print it out.
if (textLine.Length > 0)
{
if (regex.Match(textLine).Success)
{
Console.WriteLine("Match: \"{0}\" -- line: {1}", textLine, lineCount);
}
}
}
}
}
}
示例13: TestTcpTraceListener
public async Task TestTcpTraceListener()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.Server.LocalEndPoint).Port;
var traceSource = new TraceSource("UnitTestLogger");
traceSource.Listeners.Remove("Default");
traceSource.Switch.Level = SourceLevels.All;
traceSource.Listeners.Add(new TcpTraceListener(
IPAddress.Loopback, port,
new ExponentialBackoffTcpReconnectionPolicy()));
var listenerClient = await listener.AcceptTcpClientAsync();
traceSource.TraceEvent(TraceEventType.Information, 100, "Boris");
var receiverReader = new StreamReader(listenerClient.GetStream());
var line = await receiverReader.ReadLineAsync();
Assert.True(line.EndsWith("UnitTestLogger Information: 100 : Boris"));
listenerClient.Close();
listener.Stop();
traceSource.Close();
}
示例14: ProcessStream
public static async Task ProcessStream(Stream networkStream)
{
try
{
StreamReader reader = new StreamReader(networkStream);
StreamWriter writer = new StreamWriter(networkStream);
writer.AutoFlush = true;
while (true)
{
string request = await reader.ReadLineAsync();
if (request != null)
{
Console.WriteLine("Received echo: " + request);
string echo_str = await CommandResolve.Resolve(request);
if (!String.IsNullOrEmpty(echo_str))
{
await writer.WriteLineAsync(echo_str);
}
else
break; // unvalid command or command complete
}
else
break; // Client closed connection
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
示例15: ReadAllLinesAsync
public async Task<string[]> ReadAllLinesAsync(string path, Encoding encoding)
{
System.Diagnostics.Debug.WriteLine("Reading");
var lines = new List<string>();
char[] delimiterChars = { ',', ':', '\t' };
using (var reader = new StreamReader(path, encoding))
{
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines.Add(line);
}
}
//Adds items to database based on the words in each line of the file.
foreach (string item in lines)
{
string[] words = item.Split(delimiterChars);
System.Diagnostics.Debug.WriteLine("Hello from the other side");
DateTime date = new DateTime(2016, 6, 11);
if (NewItem(Convert.ToInt32(words[0]), words[1], words[2], words[3], float.Parse(words[4]), Convert.ToInt32(words[5]), Convert.ToInt32(words[6]), Convert.ToInt32(words[7]), date))
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail");
}
}
//Deletes the file when done reading.
File.Delete(path);
return lines.ToArray();
}