Issue to C# code

Peter_1985 2,806 Reputation points
2025-10-23T05:10:38.8733333+00:00

Hi,

What is wrong below?

                var lines = File.ReadAllLines(@fileName);

                string lastLine = lines.Last();

                if (!lastLine.EndsWith("\r\n"))

                {

                    using (StreamWriter sw = new StreamWriter(@d0, true, Encoding.ASCII))

                    {

                        if (!b_err3)

                        {

                            sw.WriteLine($"Please check the lines having the issues below in the file - '" + fileName + "'.");

                            sw.WriteLine();

                        }

                        sw.WriteLine("It is missing CR and LF to the line below:");

                        sw.WriteLine(lastLine);  // ✅ Only the actual line

                        sw.WriteLine();

                        b_err3 = true;

                    }

                }

The above codes does claim no CR LF to this file

https://1drv.ms/u/c/17ec75244bac022f/ETMjfHBk_UJAu0CuAmFxVhEBffhquLVWYCtjCn9vd_88Pg?e=29fClN

But there is the proper CR LF on the last line of the file. Please help.

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ravi Teja M 540 Reputation points
    2025-10-23T08:26:06.1366667+00:00

    Hello Peter,

    According to Microsoft Learn documentation, the File.ReadAllLines method removes line terminators (\r, \n, or \r\n) when reading lines into a string array, meaning the lines.Last() call will always return a string without the end-of-line characters, causing the code's condition to always evaluate as true. To accurately check for the presence of a newline at the end of a file, the content must be read in a way that preserves line endings, such as using File.ReadAllText which reads the entire file into a single string. For more details, visit Microsoft Learn.

    Regards,

    Raviteja M.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.