I took your method and changed it just a little, reducing the size of the read buffer and adding some debug statements
public static async Task<string> ReadLineAsync(this Stream stream, Encoding encoding) { const int count = 2; byte[] byteArray = Enumerable.Empty<byte>().ToArray(); using (MemoryStream ms = new MemoryStream()) { int bytesRead = 0; do { byte[] buf = new byte[count]; try { bytesRead = await stream.ReadAsync(buf, 0, count); await ms.WriteAsync(buf, 0, bytesRead); Console.WriteLine("{0:ffffff}:{1}:{2}",DateTime.Now, stream.CanRead, bytesRead); } catch (Exception e) { Console.WriteLine(e.Message + e.StackTrace); } } while (stream.CanRead && bytesRead > 0); byteArray = ms.ToArray(); return encoding.GetString(byteArray); } }
but basically it worked, as expected, from the following call:
private static void Main(string[] args) { FileStream stream = File.OpenRead(@"C:\in.txt"); Encoding encoding = Encoding.GetEncoding(1252); Task<string> result = stream.ReadLineAsync(encoding); result.ContinueWith(o => { Console.Write(o.Result); stream.Dispose(); }); Console.WriteLine("Press ENTER to continue..."); Console.ReadLine(); }
so I'm wondering if this could be something with your input file? Mine was (encoded in Windows-1252 in Notepad ++)
one two three
and my result was
Press ENTER to continue... 869993:True:2 875993:True:2 875993:True:2 875993:True:2 875993:True:2 875993:True:2 875993:True:2 875993:True:1 875993:True:0 one two three
note that โPress ENTER to continue ...โ was printed first, as expected, because the main method was called asynchronously, and CanRead always true because it means the file is readable. This is a file open state, not a state meaning that the cursor is in EOF.
source share