From b054d8cdc606201c0b25fbc11547a0db15491e8c Mon Sep 17 00:00:00 2001 From: Jan Klass Date: Sat, 22 Oct 2022 19:58:03 +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 | 5 +++-- 1 file changed, 3 insertions(+), 2 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..9e62c53f770 100644 --- a/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs +++ b/snippets/csharp/System.IO/FileStream/Overview/fstream class.cs @@ -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)); } } }