每隔x个字符插入回车



我有一个大文件,它是在没有任何记录结束引用的情况下提供给我们的。我需要每隔X个字符插入一个\r\n字符。当我尝试这样做时,在第一次插入后,长度就被打乱了。

根据记录长度插入的最佳方式是\r\n什么?

谢谢!

您可以使用Regex.Replace

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

其思想是将固定长度的X的子串捕获到捕获组号1中,然后用该组的内容(表示为$1)和rn替换它们。

在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 'rn', 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 ;
}

最新更新