Есть очень большой текстовый файл с содержимым:
5372635@5272736@2437362@827463637@262627@
И так далее. Все в одну строку.
Есть код который из этого файла читает цифры пока не встретится метка @. Если метка встретилась, то цифры ложатся в StringBuilder, потом процесс повторяется пока файл не закончится. Далее,результат, что получился в StringBuilder (например число 5372635) нужно преобразовать к типу int и поделить на число, условно 123456. То что получилось перевести в байты и записать в выходной файл. Написал такую реализацию:
void DeadSecDecoding3(string strfile)
{
string newPathFile = pathFile + ".crypto.txt";
List<string> stringlist = new List<string>();
string[] mybuf = {};
byte[] mybytes1 = { };
int j = 0;
foreach (string n in ReadParts(strfile, "@")) {
stringlist.Add(n); // каждый string ложу в List<string>, не знаю как забрать из цикла иначе :(
// mybuf = stringlist.ToArray();
}
mybuf = stringlist.ToArray(); //перевожу в массив
int strBuf = mybuf.Length;
int[] arr = new int[strBuf];
for (int i = 0; i < strBuf; i++)
{
arr[i] = Convert.ToInt32(mybuf[i]);
arr[i] = ((arr[i] / 1234567));
}
// преобразовать int[] в byte[]
mybytes1 = arr.Select(x => (byte)x).ToArray();
using (FileStream fileStream = new FileStream(newPathFile, FileMode.CreateNew, FileAccess.Write))
{
fileStream.Write(mybytes1, 0, mybytes1.Length);
fileStream.Flush();
fileStream.Close();
}}
IEnumerable ReadParts(strfile, "@") собственно открывает BinaryReader, читает каждый байт, находит метку, создает готовый объект string:
static IEnumerable<string> ReadParts(string path, string separator)
{
using (var fstream = File.OpenRead(path))
using (var reader = new BinaryReader(fstream))
{
StringBuilder sb = new StringBuilder(50);
char[] buffer = new char[32000];
int idx = 0;
while (fstream.Position < fstream.Length)
{
int charsRead = reader.Read(buffer, 0, buffer.Length);
for (int i = 0; i < charsRead; i++)
{
char ch = buffer[i];
if (ch == separator[idx])
{
idx++;
if (idx == separator.Length)
{
yield return sb.ToString();
sb.Clear();
idx = 0;
}
}
else
{
sb.Append(ch);
}
}
}
if (sb.Length > 0) yield return sb.ToString();
}
}
Проблема заключается в том, что я не уверен, хватит ли памяти у StringBuilder и List stringlist, т.к. мой IEnumerable оказался чрезвычайно медленной вещью. Обработка файла в 700Мб занимает видимо бесконечное время. Зацикленности в отладчике не выявил, но я не дождался :(
Я написал еще одну "корявую" реализацию без IEnumerable, просто используя циклы, но она успешно обрабатывает файлы до ~160Мб и я не смог побороть проблему с таким участком кода:
FileStream fs = new FileStream(newstrFile, FileMode.Open, FileAccess.Read);
long nBytesRead = fs.Length;
int nLines = (int)(nBytesRead / nCols) + 1;
string[] lines = new string[nBytesRead];
т.к. если файл больше ~160Мб - то размера string[] lines просто не хватает :(
Вопросы сформировались такие: как можно заменить мой IEnumerable на что-то более быстрое? Или мой подход к проблеме вовсе некорректен? И по последнему кусочку кода как обойти MemoryException на участке
string[] lines = new string[nBytesRead];
и что можно/нужно изменить, чтобы этот вариант не кушал там много памяти?
Ниже привожу полную реализацию:
void DeadSecDecoding(string strfile)
{
string newstrFile = strfile;
string newPathFile = pathFile + ".crypto.txt";
int nCols = 16;
FileStream fs = new FileStream(newstrFile, FileMode.Open, FileAccess.Read);
long nBytesRead = fs.Length;
int nLines = (int)(nBytesRead / nCols) + 1;
string[] lines = new string[nBytesRead]; // соответственно MemoryException
int nBytesToRead = 0;
int[] arr = { };
byte[] mybytes1;
string[] lines2 = { };
int strBuf = lines.Length;
bool check = false;
int i = 0;
@m1:
if (check == false){
for (i = 0; i < nBytesRead; i++)
{
StringBuilder nextLine = new StringBuilder();
nextLine.Capacity = 4 * nCols;
for (int j = 0; j < nBytesRead; j++)
{
int nextByte = fs.ReadByte();
nBytesToRead++;
char nextChar = (char)nextByte; // получаем байт
if (nextChar == '@') { break; }
if (nextByte < 0) { check = true; goto m1; }
nextLine.Append(nextChar);
}
lines[i] = nextLine.ToString();
}
}
fs.Flush();
fs.Close();
string[] copied = (from elem in lines where elem != null select elem).ToArray();
int copyLenght = copied.Length;
int[] arrNew = new int[copyLenght];
for (int j = 0; j < copyLenght; j++)
{
arrNew[j] = Convert.ToInt32(copied[j]);
arrNew[j] = ((arrNew[j] / 1234567));
}
mybytes1 = arrNew.Select(x=>(byte)x).ToArray();
using (FileStream fileStream = new FileStream(newPathFile, FileMode.Create, FileAccess.Write))
{
fileStream.Write(mybytes1, 0, mybytes1.Length);
fileStream.Flush();
fileStream.Close();
}
}
p.s. прошу не пинать ногами, C# изучаю всего 5-6 месяцев :-(