From 27c9283d12c0971abbc61b36a9a5be8ce4bc16bf Mon Sep 17 00:00:00 2001 From: Jan Klass Date: Sat, 22 Oct 2022 19:54:31 +0200 Subject: [PATCH] Fix snippet buffered read logic The snippet generates a file with 215 bytes. It reads the file with a 1024 byte buffer. While this works with a new 0-initialized buffer, the buffered reading misses using the returned read bytes count. A file with > 1024 bytes will reuse the now non-0 buffer and print unintended values. Fix buffered reading to be technically correct and work for arbitrary file contents. Fixes #4141 --- .../csharp/System.IO/FileStream/Overview/fstream class.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs b/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs index dc2511b4313..38d7df995e5 100644 --- a/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs +++ b/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs @@ -24,7 +24,7 @@ public static void Main() AddText(fs, "\r\nand this is on a new line"); AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n"); - for (int i=1;i < 120;i++) + for (int i = 1; i < 120; i++) { AddText(fs, Convert.ToChar(i).ToString()); } @@ -35,9 +35,10 @@ public static void Main() { byte[] b = new byte[1024]; UTF8Encoding temp = new UTF8Encoding(true); - while (fs.Read(b,0,b.Length) > 0) + int readLen; + while ((readLen = fs.Read(b, 0, b.Length)) > 0) { - Console.WriteLine(temp.GetString(b)); + Console.WriteLine(temp.GetString(b, 0, readLen)); } } }