簡體   English   中英

插入回車符,每x個字符返回

[英]insert carriage return every x characters

我有一個大文件,沒有任何記錄結尾引用。 我需要在每個X字符中插入一個\\ r \\ n。 當我嘗試這樣做時,第一次插入后,長度就會變大。

根據記錄長度插入\\ r \\ n的最佳方法是什么?

謝謝!

您可以使用Regex.Replace

Regex.Replace(
    longText
,   "(.{5})" // Replace 5 with X
,   "$1\r\n"
)

這個想法是將固定長度X子字符串捕獲到捕獲組編號1中,然后將其替換為該組的內容(表示為$1 ),后跟\\r\\n

ideone上的演示。

這樣的事情應該做。 它采用由具有給定編碼的固定長度記錄組成的源文件,並將其轉換為“常規” CR + LF分隔記錄。 當然,有一個隱含的假設,即文件包含文本數據。

public static void ConvertFixedLengthRecordsToDelimitedRecords( FileInfo sourceFile , Encoding sourceEncoding , int recordLength )
{
  if ( sourceFile == null ) throw new ArgumentNullException("sourceFile");
  if ( !sourceFile.Exists ) throw new ArgumentException("sourceFile does not exist" , "sourceFile" ) ;
  if ( sourceEncoding == null ) throw new ArgumentNullException("sourceEncoding");
  if ( recordLength < 1 ) throw new ArgumentOutOfRangeException("recordLength");

  // create a temporary file in the temp directory
  string tempFileName = Path.GetTempFileName() ;

  // copy the source file to the temp file 1 record at a time, writing each record as a line.
  //
  // NOTE: If the source data contains '\r', '\n' or '\r\n', you'll get short records in the output
  // You might consider throwing an exception or figuring out how to deal with that.
  using ( FileStream   inStream  = sourceFile.Open( FileMode.Open , FileAccess.Read , FileShare.Read ) ) 
  using ( StreamReader input     = new StreamReader( inStream , sourceEncoding ) )
  using ( Stream       outStream = File.Open( tempFileName , FileMode.Truncate , FileAccess.Write , FileShare.Read ) )
  using ( StreamWriter output    = new StreamWriter( outStream , Encoding.UTF8 ) )
  {
    char[] buf = new char[recordLength];
    int bufl ;

    while ( 0 != (bufl = input.ReadBlock( buf , 0 , buf.Length )) )
    {
      output.WriteLine(buf,0,bufl) ;
    }
  }

  // at this point, the temporary file contains the fixed-length source records at CR+LF terminated lines.
  // We just need to replace the source file with the temp file.
  FileInfo tempFile = new FileInfo( tempFileName ) ;
  string backupFileName = sourceFile.FullName + ".bak" ;
  File.Delete( backupFileName ) ;
  tempFile.Replace( sourceFile.FullName , backupFileName ) ;

  return ;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM