我有一个正在使用 c# 中的 TextFieldParser 类读取的文本文件。这个文件有 CRLF 作为我可以使用 Notepad++ 看到的换行符。该文件的几行以 LF 作为换行符。
我需要获取这些换行符之间的最大出现次数,然后用空白替换最少使用的次数,以便文件具有相同的换行符。
到目前为止,这是我的代码,
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);
}
它不计算任何出现的换行符。
我做错了什么,如何计算文件中所有换行符的数量?