我想讀與C#的文本文件,即格式如下:C# - 不規則換行符讀取文件
this is a line\r\n
this is a line\r
\r\n
this is a line\r
\r\n
this is a line\r
\r\n
this is a line\r\n
this is a line\r
\r\n
etc...
我從文件讀取每一行
StreamReader.ReadLine()
但不保留換行符。我需要知道/檢測有哪些新的行字符,因爲我正在計算每行的字節數。例如:
如果線與字符\r
結束,線路包括:((nr-of-bytes-in-line) + 1 byte)
字節(根據編碼類型的課程),如果符合\r\n
結束時,線包括:((nr-of-bytes-in-line) + 2 bytes)
字節。
編輯:
我有解決方案的基礎上,以色列壇的答案。順便說一句:喬恩Skeet也建議它。我已經實現了ReadLine的重寫版本,以便它包含新的行字符。這是重寫的函數的代碼:
public override String ReadLine()
{
StringBuilder sb = new StringBuilder();
while (true)
{
int ch = Read();
if (ch == -1)
{
break;
}
if (ch == '\r' || ch == '\n')
{
if (ch == '\r' && Peek() == '\n')
{
sb.Append('\r');
sb.Append('\n');
Read();
break;
}
else if(ch == '\r' && Peek() == '\r')
{
sb.Append('\r');
break;
}
}
sb.Append((char)ch);
}
if (sb.Length > 0)
{
return sb.ToString();
}
return null;
}
我相信你基本上必須在那種情況下自己重新實現ReadLine()。 –
請使用ReadLine。如果需要字節計數,請一次讀取一個字符。 – jdweng
不,我這樣做:'string line = sr.ReadLine(); int nrOfBytes = Encoding.GetByteCount(line);'但是需要檢測有什麼樣的新行字符,無論是'\ r'還是'\ r \ n'。所以我可以這樣做:'nrOfBytes + = Encoding.GetByteCount(UNKNOWN-NEW-LINE-CHAR);' – DrGrid