感谢大家的建议。我很惊讶没有找到易于重用的东西,因此我创建了一个简单的函数,并将其包含在此处。请注意,它只是查找第一个换行符(\n 或 \r\n)并将其作为匹配项返回。足以满足我的需求,但可能不够强大。
public bool TryDetectNewLine(string path, out string newLine)
{
using (var fileStream = File.OpenRead(path))
{
char prevChar = '\0';
// Read the first 4000 characters to try and find a newline
for (int i = 0; i < 4000; i++)
{
int b;
if ((b = fileStream.ReadByte()) == -1) break;
char curChar = (char)b;
if (curChar == '\n')
{
newLine = prevChar == '\r' ? "\r\n" : "\n";
return true;
}
prevChar = curChar;
}
// Returning false means could not determine linefeed convention
newLine = Environment.NewLine;
return false;
}
}
Run Code Online (Sandbox Code Playgroud)