How to calculate count of line feed or carriage return characters from a text file in C#?

817 Views Asked by At

I have a text file that I am reading using TextFieldParser class in c#. This file has CRLF as the newline character that I can see using Notepad++. Few lines of this file have LF as the newline character.

I need to get the count of maximum occurrence between those newline characters and then replace the least used with blank so the file has the same new line character.

Here is my code so far,

if (File.Exists(path))
{
    List<string> delimiters = new List<string> { ";", "-", ",", "|" };
    List<string> linebreakchars = new List<string> { "\r", "\r\n", "\n"};
    Dictionary<string, int> counts = delimiters.ToDictionary(key => key, value => 0);
    Dictionary<string, int> countNewLineChars = linebreakchars.ToDictionary(key => key, value => 0);
    int counter = 0;
    int counterLine = 0;
    string line;
    // Read the file and display it line by line.
    System.IO.StreamReader file =
        new System.IO.StreamReader(path);
    while ((line = file.ReadLine()) != null)
    {
        foreach (string c in delimiters)
            counts[c] = line.Count(t => t == Convert.ToChar(c));
        counter++;
        foreach(string ln in linebreakchars)
            countNewLineChars[ln] = line.Count(t => t.ToString() == ln);
        counterLine++;
    }
    var delimiter = counts.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
    var newLineChar = countNewLineChars.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
    string text = File.ReadAllText(path);
    file.Close();
    switch (newLineChar)
    {
        case "\r":
            text = Regex.Replace(text, @"(?<!\r)\n+", "");
            break;
        case "\r\n":
            text = Regex.Replace(text, @"(?<!\r)\n+", "");
            break;
        case "\n":
            text = Regex.Replace(text, @"(?<!\n)\r\n+", "");
            break;
    }
    File.WriteAllText(path, text);
}

It doesn't count any occurrence of the line break characters.

What am I doing wrong and how do I get the count of all newline characters of my file?

0

There are 0 best solutions below