本文整理汇总了C#中System.IO.StreamReader.ReadAsync方法的典型用法代码示例。如果您正苦于以下问题:C# StreamReader.ReadAsync方法的具体用法?C# StreamReader.ReadAsync怎么用?C# StreamReader.ReadAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamReader
的用法示例。
在下文中一共展示了StreamReader.ReadAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: logFromStream
private async Task logFromStream(Stream stream, CancellationToken token, string category, Func<bool> isComplete)
{
char[] buffer = new char[128];
using (var sr = new StreamReader(stream))
{
while (true)
{
token.ThrowIfCancellationRequested();
var outBytesRead = await sr.ReadAsync(buffer, 0, buffer.Length);
if (outBytesRead == 0)
{
if (isComplete())
break;
else
await Task.Delay(100);
}
else
{
var outText = new string(buffer, 0, outBytesRead);
if (!string.IsNullOrEmpty(outText))
this.newLogEntry(outText, category, true, true);
}
}
}
}
示例2: ReadAsync
public override async Task ReadAsync(StreamReader reader)
{
var buffer = new char[valorFixo.Length];
var read = await reader.ReadAsync(buffer, 0, buffer.Length);
if (read != buffer.Length || new string(buffer) != valorFixo)
throw new LeituraException($"O valor fixo '{valorFixo}' não foi encontrado.");
}
示例3: ReadBlockAsync
private async Task<DataBlock> ReadBlockAsync(StreamReader reader, DataBlock target)
{
var readBytes = await reader.ReadAsync(target.Data, 0, BufferSize);
if (readBytes != BufferSize)
{
target.ResizeData(readBytes);
}
return target;
}
示例4: Create
public static async Task<IHttpPost> Create(StreamReader reader, int postContentLength)
{
char[] rawEncoded = new char[postContentLength];
int readBytes = await reader.ReadAsync(rawEncoded, 0, rawEncoded.Length);
byte[] raw = Encoding.UTF8.GetBytes(rawEncoded, 0, readBytes);
return new HttpPost(raw, readBytes);
}
示例5: CreateListener
public static async void CreateListener(Action<string> action, TcpClient tcpClient)
{
var networkStream = tcpClient.GetStream();
var r = new StreamReader(networkStream);
var buffer = new char[1];
while (true)
{
if (r.EndOfStream)
{
Task.Delay(500);
continue;
}
await r.ReadAsync(buffer, 0, buffer.Length);
action(new string(buffer));
}
}
示例6: ReadStreamAsync
/// <summary>
/// Utility method that fills a StringBuilder
/// </summary>
/// <param name="data">Stream containing document data.</param>
/// <returns>Content of the stream as a string.</returns>
public static async Task<string> ReadStreamAsync(Stream data, int blockSize=4096)
{
var buffer = new char[blockSize];
var builder = new StringBuilder();
using (var reader = new StreamReader(data))
{
while (!reader.EndOfStream)
{
// StreamReader.ReadAsync() returns number of *chars* read, not number of bytes, in
// spite of what the API docs say. I read the code (MW 2015.11.06)
var charsRead = await reader.ReadAsync(buffer, 0, blockSize).ConfigureAwait(false);
builder.Append(buffer, 0, charsRead);
}
}
return builder.ToString();
}
示例7: AnalyzeAsync
/// <summary>
/// Asynchronous method to analyze the data stream.
/// </summary>
/// <param name="data">Data stream to analyze.</param>
/// <param name="blockSize">Max number of characters to read at a time.</param>
/// <returns>Result of the analysis.</returns>
public async Task<IAnalyzerResult> AnalyzeAsync(Stream data, int blockSize = 1024)
{
var result = new CharacterAnalyzerResult();
var buffer = new char[blockSize];
using (var reader = new StreamReader(data))
{
var lastCharType = CharacterType.Invalid;
while (!reader.EndOfStream)
{
var count = await reader.ReadAsync(buffer, 0, blockSize).ConfigureAwait(false);
lastCharType = AnalyzeBuffer(buffer, count, result, lastCharType);
}
}
return result;
}
示例8: WaitForPrompt
private static async Task<bool> WaitForPrompt(StreamReader reader, string prompt)
{
var buffer = new char[1024];
int read;
var readString = string.Empty;
while ((read = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
readString += new string(buffer, 0, read);
if (readString.TrimEnd().EndsWith(prompt))
{
Console.Write(readString);
return true;
}
}
Console.Write(readString);
return false;
}
示例9: HandleClientAccessPolicy
public static async Task HandleClientAccessPolicy(TcpClient client, string policyResponse)
{
using (var clientStream = client.GetStream())
{
string request = string.Empty;
var reader = new StreamReader(clientStream);
var charArray = new char[2048];
var length = await reader.ReadAsync(charArray, 0, 2048);
request = new String(charArray, 0, length);
if (request == PolicyRequest)
{
var writer = new StreamWriter(clientStream, Encoding.UTF8);
writer.AutoFlush = true;
await writer.WriteAsync(policyResponse);
}
}
client.Close();
}
示例10: ReadStreamToEnd
static async Task ReadStreamToEnd(StreamReader stream, IObserver<string> observable) {
try {
var readBuffer = new char[1];
var lineBuffer = new StringBuilder();
while ((await stream.ReadAsync(readBuffer, 0, 1).ConfigureAwait(false)) > 0) {
var c = readBuffer[0];
lineBuffer.Append(c);
// This does not account for unterminated lines.... like 'verifying download...'
// We would be able to do this by sending the data also byte by byte to the receivers, but for little gain.
if (c != '\r' && c != '\n')
continue;
observable.OnNext(lineBuffer.ToString());
lineBuffer.Clear();
}
if (lineBuffer.Length > 0)
observable.OnNext(lineBuffer.ToString());
} finally {
observable.OnCompleted();
}
}
示例11: TryReadTextFileAsync
public async Task<TryResult<string>> TryReadTextFileAsync(string path, CancellationToken cancellationToken)
{
var contentStringBuilder = new StringBuilder();
var operationSucceeded = await TryReadFileCommonAsync(path, async stream =>
{
using (var reader = new StreamReader(stream))
{
var buffer = new char[BufferSize];
while (reader.Peek() > 0)
{
if (cancellationToken.IsCancellationRequested)
return false;
var charsRead = await reader.ReadAsync(buffer, 0, BufferSize);
contentStringBuilder.Append(buffer, 0, charsRead);
}
return true;
};
}).ConfigureAwait(false);
return TryResult.Create(operationSucceeded, operationSucceeded ? contentStringBuilder.ToString() : string.Empty);
}
示例12: LoadFileAsync
private async Task<Document> LoadFileAsync(ILoader loader, string path, CancellationToken cancellationToken)
{
try
{
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
using (var reader = new StreamReader(file))
{
var count = 0;
var buffer = new char[4096];
while ((count = await reader.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
{
// Check for cancellation
cancellationToken.ThrowIfCancellationRequested();
// Add the data to the document
if (!loader.AddData(buffer, count))
{
throw new IOException("The data could not be added to the loader.");
}
}
return loader.ConvertToDocument();
}
}
catch
{
loader.Release();
throw;
}
}
示例13: Procesar
/// <summary>
/// Lee el archivo en pedazos de 4096 bytes, y llena el diccionario indicando
/// que letras existen en el archivo y cuantas veces aparece cada una de ellas.
/// </summary>
/// <returns>
/// Retorna una tarea ya que es un proceso que puede ejecutarse en otro
/// hilo para no bloquear la UI.
/// </returns>
public async Task<DocumentoProcesado> Procesar()
{
var palabras = new SortedDictionary<string, int>();
var letras = new SortedDictionary<char, int>();
var signos = new SortedDictionary<char, int>();
var simbolos = new SortedDictionary<char, int>();
int palabrasCantidad = 0;
int letrasCantidad = 0;
int signosCantidad = 0;
int simbolosCantidad = 0;
int bytesLeidos = 0;
// Se asume que todos los archivos tendrán encoding de UTF8
// a menos que el sistema pueda detectarlo por el order de bytes.
using (var reader = new StreamReader(rutaArchivo, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: bufferSize))
{
var letrasPalabra = new List<char>();
var buffer = new char[bufferSize];
var count = 0;
do
{
// se lee un fragmento de 4096 bytes del archivo
count = await reader.ReadAsync(buffer, 0, bufferSize);
// Se analiza cada una de esas 4096 letras leídas
// y si no se encuentran en el diccionario aún se
// agregan con valor de uno,
// pero si la letra ya existe en el diccionario,
// solo se incrementa en uno su valor.
for (int i = 0; i < count; i++)
{
var caracter = buffer[i];
if (char.IsLetter(caracter))
{
letrasCantidad++;
var c = char.ToLowerInvariant(caracter);
letrasPalabra.Add(c);
if (letras.ContainsKey(c))
{
letras[c]++;
}
else
{
letras.Add(c, 1);
}
}
else if (letrasPalabra.Count > 0)
{
if (letrasPalabra.Count <= 5)
{
palabrasCantidad++;
var palabra = new string(letrasPalabra.ToArray()).ToLowerInvariant();
if (palabras.ContainsKey(palabra))
{
palabras[palabra]++;
}
else
{
palabras.Add(palabra, 1);
}
}
letrasPalabra.Clear();
}
if (char.IsPunctuation(caracter))
{
signosCantidad++;
if (signos.ContainsKey(caracter))
{
signos[caracter]++;
}
else
{
signos.Add(caracter, 1);
}
}
if (char.IsSymbol(caracter))
//.........这里部分代码省略.........
示例14: clientThread
/*
*METHOD : clientThread
*
*DESCRIPTION : Method to listen to a spesific users pipe
* Is creates the connection, listens for a command
* then acts acordingly based on that command
*
*PARAMETERS : object sender: Opject relaying information on where the even call came from
* EventArgs e: Object that contains data about the event
*
*RETURNS : void
*
*/
private async void clientThread(object clientPipeName)
{
string serverName = "";
string pipeName = (string)clientPipeName;
NamedPipeClientStream client;
NamedPipeServerStream server;
StreamReader input;
StreamWriter output;
DAL dal = new DAL();
string userName = "";
//set up pipe security
PipeSecurity ps = new PipeSecurity();
System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
ps.AddAccessRule(par);
Logger.Log("Client thread started");
//wait for user to connect
server = new NamedPipeServerStream(clientPipeName + "service", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
server.WaitForConnection();
input = new StreamReader(server);
Logger.Log("Client connected to pipe: " + clientPipeName);
//get the name of the computer to connect back to
serverName = input.ReadLine();
//connect back
try
{
client = new NamedPipeClientStream(serverName, clientPipeName + "User");
client.Connect(30);
output = new StreamWriter(client);
Logger.Log("User thread connected to pipe: " + clientPipeName);
//start loop to watch the pipe
while (!Done)
{
//async read from pipe
char[] temp = new char[5000];
await input.ReadAsync(temp, 0, 5000);
//move data from pipe to a string (padded with somthing, not sure what)
string userCommand = new string(temp);
//all commands end in a period. if there is no period then the user left
if (!userCommand.Contains("."))
{
Logger.Log("Pipe: " + clientPipeName + "userLeft");
//close connection
output.Dispose();
input.Dispose();
//remove from repo
clients.DeleteClient((string)clientPipeName);
break;
}
//if the command is valid
//remove the period and all padded data
userCommand = userCommand.Remove(userCommand.IndexOf('.'));
Logger.Log("Pipe: " + clientPipeName + " Got Command: " + userCommand);
//select the command entered
if (userCommand == "NewUser")
{
Logger.Log("Pipe: " + clientPipeName + "in newUser command code");
//read in user name
userName = input.ReadLine();
//add to database
output.WriteLine("OK");
output.Flush();
//if user not in database add
dal.OpenConnection();
bool isUserTaken = dal.IsNameInDatabase(userName);
dal.CloseConnection();
if (isUserTaken == false)
{
dal.OpenConnection();
dal.StoreUserName(userName);
dal.InitializeUserInLeaderboard(userName, 1);
dal.CloseConnection();
}
}
else if (userCommand == "GetQuestion")
{
//.........这里部分代码省略.........
示例15: ProcessConnection
/// <summary>
/// Handle an incoming SMTP connection, from connection to completion.
/// </summary>
/// <param name="parameters">SmtpProxyConnectionArguments object containing all parameters for this connection.</param>
private async void ProcessConnection(object parameters)
{
// Cast the passed-in parameters back to their original objects.
SmtpProxyConnectionArguments arguments = (SmtpProxyConnectionArguments)parameters;
// The overall number of bytes transmitted on this connection.
ulong bytesTransmitted = 0;
TcpClient client = null;
Stream clientStream = null;
StreamReader clientStreamReader = null;
StreamWriter clientStreamWriter = null;
string ip = "";
try
{
client = arguments.TcpClient;
clientStream = client.GetStream();
// Placeholder variables to be populated throughout the client session.
NetworkCredential credential = arguments.RemoteServerCredential;
string fromAddress = "";
string identity = "";
List<string> toList = new List<string>();
bool sending = false, inPlainAuth = false, inLoginAuth = false;
// A byte array to streamline bit shuffling.
char[] buffer = new char[Constants.SMALLBUFFERSIZE];
// Capture the client's IP information.
PropertyInfo pi = clientStream.GetType().GetProperty("Socket", BindingFlags.NonPublic | BindingFlags.Instance);
ip = ((Socket)pi.GetValue(clientStream, null)).RemoteEndPoint.ToString();
if (ip.IndexOf(":") > -1)
ip = ip.Substring(0, ip.IndexOf(":"));
// If the IP address range filter contains the localhost entry 0.0.0.0, check if the client IP is a local address and update it to 0.0.0.0 if so.
if (arguments.AcceptedIPs.IndexOf("0.0.0.0") > -1)
{
if (ip == "127.0.0.1")
ip = "0.0.0.0";
else
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress hostIP in hostEntry.AddressList)
{
if (hostIP.ToString() == ip)
{
ip = "0.0.0.0";
break;
}
}
}
}
clientStreamReader = new StreamReader(clientStream);
clientStreamWriter = new StreamWriter(clientStream);
clientStreamWriter.AutoFlush = true;
// Validate that the IP address is within an accepted range.
if (!ProxyFunctions.ValidateIP(arguments.AcceptedIPs, ip))
{
ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "Connection rejected from {" + ip + "} due to its IP address.", Proxy.LogLevel.Warning, LogLevel);
await Functions.SendStreamStringAsync(clientStreamWriter, "500 IP address [" + ip + "] rejected.\r\n");
ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "S: 500 IP address [" + ip + "] rejected.", Proxy.LogLevel.Raw, LogLevel);
if (clientStream != null)
clientStream.Dispose();
if (client != null)
client.Close();
return;
}
ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "New connection established from {" + ip + "}.", Proxy.LogLevel.Information, LogLevel);
// Send our welcome message.
await Functions.SendStreamStringAsync(clientStreamWriter, "220 " + WelcomeMessage + "\r\n");
ProxyFunctions.Log(LogWriter, SessionId, arguments.ConnectionId, "220 " + WelcomeMessage, Proxy.LogLevel.Raw, LogLevel);
// Instantiate an SmtpClient for sending messages to the remote server.
using (OpaqueMail.Net.SmtpClient smtpClient = new OpaqueMail.Net.SmtpClient(arguments.RemoteServerHostName, arguments.RemoteServerPort))
{
smtpClient.EnableSsl = arguments.RemoteServerEnableSsl;
smtpClient.Credentials = arguments.RemoteServerCredential;
if (arguments.SmimeValidCertificates != null)
smtpClient.SmimeValidCertificates = arguments.SmimeValidCertificates;
// Loop through each received command.
string command = "";
bool stillReceiving = true;
while (Started && stillReceiving)
{
int bytesRead = await clientStreamReader.ReadAsync(buffer, 0, Constants.SMALLBUFFERSIZE);
//.........这里部分代码省略.........