Thank you for reaching out.
The issue occurred because of an incorrect regular expression (regex) and incomplete handling of the end-of-line (EOL) conditions.
- Incorrect Regex Pattern:
Your regex used (?<eol>\r\n\r\n|$) which looks for two consecutive CRLF sequences instead of one. As a result, the last line or any single \r\n line ending wasn’t matched correctly — leading to false “missing both LF and CR” detections.
- EOL Detection Issue:
The final line of most text files does not have an EOL marker, because the file ends there. Your code didn’t properly handle that case, so it reported the last line as missing both LF and CR.
- Logic Simplification Needed:
Some conditions like b_err3 = false in if statements were incorrect; it should be checked as if (!b_err3) to avoid assignment errors.
var rx = new Regex(@"(?<line>[^\r\n]*)(?<eol>\r\n|\r|\n|$)");
foreach (Match m in rx.Matches(str31))
{
var linee = m.Groups["line"].Value;
var eole = m.Groups["eol"].Value;
// Skip completely empty matches
if (string.IsNullOrEmpty(linee) && string.IsNullOrEmpty(eole))
continue;
switch (eole)
{
case "\r\n":
// Correct EOL - no issue
break;
case "\n":
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 for the line below:");
sw.WriteLine(linee);
sw.WriteLine("");
b_err3 = true;
}
break;
case "\r":
if (!b_err3)
{
sw.WriteLine("Please check the lines having the issues below in the file - 'filename'");
sw.WriteLine("");
sw.WriteLine("It is missing LF for the line below:");
sw.WriteLine(linee);
sw.WriteLine("");
b_err3 = true;
}
break;
case "":
// Handles last line without EOL marker
if (!string.IsNullOrEmpty(linee) && !b_err3)
{
sw.WriteLine("Please check the lines having the issues below in the file - 'filename'");
sw.WriteLine("");
sw.WriteLine("The line below is missing both LF and CR (last line without EOL):");
sw.WriteLine(linee);
sw.WriteLine("");
b_err3 = true;
}
break;
}
}
``
Changed in code
- Removed:
\r\n\r\n from regex → replaced with \r\n|\r|\n|$
Because two CRLFs were incorrect; single EOL patterns handle all cases properly.
- Fixed:
if (b_err3 = false) → changed to if (!b_err3)
To check condition instead of accidentally assigning false.
- Added: Empty line skip at top of loop
Prevents false positives for blank matches at EOF.
- Adjusted:
case "" logic
Now reports only when the last line actually exists and has no EOL.
If the issue has been resolved, please click "Accept Answer".