我有一个文本文件,我正在使用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);
}
它不计算任何出现的换行符。
我做错了什么以及如何获取文件中所有换行符的计数?