Что-то, как это должно сделать вас. Он берет исходный файл, состоящий из записей фиксированной длины с заданным кодированием и преобразует его в «обычные» записи с ограничением 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 ;
}
«длина завинчивается после первой вставки», что вы подразумеваете под этим? Ожидаете ли вы вставить новые символы без изменения исходной длины строки? –
Вам придется работать в обратном направлении от конца строки. –
Я не нашел ничего, что касается разбора строки x символов с итерацией в обратном ... может ли кто-нибудь предоставить ссылку? – ErocM