2016-04-12 26 views
1

我想讀與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; 
    } 
+3

我相信你基本上必須在那種情況下自己重新實現ReadLine()。 –

+0

請使用ReadLine。如果需要字節計數,請一次讀取一個字符。 – jdweng

+0

不,我這樣做:'string line = sr.ReadLine(); int nrOfBytes = Encoding.GetByteCount(line);'但是需要檢測有什麼樣的新行字符,無論是'\ r'還是'\ r \ n'。所以我可以這樣做:'nrOfBytes + = Encoding.GetByteCount(UNKNOWN-NEW-LINE-CHAR);' – DrGrid

回答

1

這是Readline正根據.NET資源實現方式:

// Reads a line. A line is defined as a sequence of characters followed by 
     // a carriage return ('\r'), a line feed ('\n'), or a carriage return 
     // immediately followed by a line feed. The resulting string does not 
     // contain the terminating carriage return and/or line feed. The returned 
     // value is null if the end of the input stream has been reached. 
     // 
     public virtual 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') Read(); 
        return sb.ToString(); 
       } 
       sb.Append((char)ch); 
      } 
      if (sb.Length > 0) return sb.ToString(); 
      return null; 
     } 

,你可以看到,如果你可以添加一個句子是這樣的:

if (ch == '\r') 
{ 
    //add the amount of bytes wanted 
} 
if (ch == '\n') 
{ 
    //add the amount of bytes wanted 
} 

或做任何你想要的操作。

+2

或者只是改變它以將'\ r'和'\ n'附加到'StringBuilder'。 – juharr

+1

我要試試這個,我將不得不實現我自己的ReadLine版本(一個被覆蓋的版本)。 – DrGrid

+1

我已經在自定義類中實現了ReadLine的重寫版本,我認爲它可以工作。我正在測試獲得某一行字節數的最佳方法,但這是我尋找的解決方案。 – DrGrid