public void MakeFileFromArchive(string Path, System.IO.BinaryReader BinFileReader, DLA.BufferedFileInfo FileInfo) { do { FileInfo.IsFolder = false; FileInfo.NotReadFile = false; ++BinFileReader.BaseStream.Position; ///| this.Method = BinFileReader.ReadInt16(); ///|Method ++BinFileReader.BaseStream.Position; ///|Method| FileInfo.FileAttributes = (System.IO.FileAttributes)BinFileReader.ReadInt32(); ///|Method|Атрибуты ++BinFileReader.BaseStream.Position; ///|Method|Атрибуты| FileInfo.FileCreationTime = new DateTime(BinFileReader.ReadInt64()); ///|Method|Атрибуты|Д ++BinFileReader.BaseStream.Position; ///|Method|Атрибуты|Д| FileInfo.FileLastAccessTime = new DateTime(BinFileReader.ReadInt64()); ///|Method|Атрибуты|Д|Д ++BinFileReader.BaseStream.Position; ///|Method|Атрибуты|Д|Д| FileInfo.FileLastWriteTime = new DateTime(BinFileReader.ReadInt64()); ///|Method|Атрибуты|Д|Д|Д ++BinFileReader.BaseStream.Position; ///|Method|Атрибуты|Д|Д|Д| ++BinFileReader.BaseStream.Position; FileInfo.FileName = ""; for (this.buff = BinFileReader.ReadChar(); this.buff != Archive_reader.FileNameDelim; this.buff = BinFileReader.ReadChar()) { FileInfo.FileName += this.buff; } ///|Method|Атрибуты|Д|Д|Д|-Name| ++BinFileReader.BaseStream.Position; FileInfo.FileDirectoryName = ""; for (this.buff = BinFileReader.ReadChar(); this.buff != Archive_reader.FileNameDelim; this.buff = BinFileReader.ReadChar()) { FileInfo.FileDirectoryName += this.buff; } ///|Method|Атрибуты|Д|Д|Д|-Name|-Path| if ((FileInfo.FileAttributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory) { FileInfo.IsFolder = true; ///|Method|Атрибуты|Д|Д|Д|-Name|-Path| } else { FileInfo.FileLength = BinFileReader.ReadInt64(); ///|Method|Атрибуты|Д|Д|Д|-Name|-Path|12345 } ++BinFileReader.BaseStream.Position; ///|Method|Атрибуты|Д|Д|Д|-Name|-Path|12345| /// Создание файла/папки FileInfo.MakeFile(Path); /// Запись в файл if (!FileInfo.IsFolder) { /// /// Конкретизировать обработчик ошибок /// Перехватывает пользовательские исключения /// try { /// Изменение указателя в потоке при невозможности записи в файл if (FileInfo.NotReadFile) { BinFileReader.BaseStream.Position += FileInfo.FileLength; } else { /// Проверка на повреждение последнего файла в архиве if ((BinFileReader.BaseStream.Position + FileInfo.FileLength) <= BinFileReader.BaseStream.Length) { /// /// Пишем в bFS с архива /// this.TemporaryFile = System.IO.Path.GetTempFileName(); //using (System.IO.FileStream bFS = new System.IO.FileStream(System.Environment.CurrentDirectory + FileInfo.PathModifier(Path), System.IO.FileMode.Open, System.IO.FileAccess.Write)) using (System.IO.FileStream bFS = new System.IO.FileStream(this.TemporaryFile, System.IO.FileMode.Open, System.IO.FileAccess.Write)) { for (FileInfo.PosBuff = 0; FileInfo.PosBuff < FileInfo.FileLength; ++FileInfo.PosBuff) { this.ByteBuff = BinFileReader.ReadByte(); bFS.WriteByte(this.ByteBuff); } bFS.Close(); } /// Открываем Temp file на чтение для работы метода using (System.IO.FileStream bFS = new System.IO.FileStream(this.TemporaryFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { /// /// Настройка пути к папке со сборками /// this.NeededAssembly = this.WorkFolderPath + System.IO.Path.DirectorySeparatorChar + AssemblysFolderName + System.IO.Path.DirectorySeparatorChar + @"M" + this.Method + @".dll"; /// /// Загрузка сборки сборки /// try { if (System.IO.File.Exists(this.NeededAssembly)) { this.MethodAssembly = System.Reflection.Assembly.LoadFile(this.NeededAssembly); } else { Console.WriteLine("Файл отсутствуeт: {1} Переустановите программу!", this.NeededAssembly); throw new Exception(); } } catch { Console.WriteLine("Сборка {0} повреждена. Загрузите ее заново!", this.NeededAssembly); throw new Exception(); } /// TDOD: Проанализировать возможность выполнения через System.AppDomain.CurrentDomain.ExecuteAssembly /// Без загрузки в текуший домен /// ///--------------------------------------------------- /// /// Вытаскивание конструкторов из класса и вызов 0ого. /// TODO: Конкретизировать выбор конструктора /// this.AssemblyConstructorType = this.MethodAssembly.GetType("Method.Method"); this.ClassConstructors = this.AssemblyConstructorType.GetConstructors(); //System.Reflection.ConstructorInfo ci = ti.GetConstructor(new Type[1] { tis/*this.TemporaryFile.GetType()*//*, true.GetType()*/}); using (System.IO.FileStream DestinationFileStream = new System.IO.FileStream(System.Environment.CurrentDirectory + FileInfo.PathModifier(Path), System.IO.FileMode.Open, System.IO.FileAccess.Write)) { if (this.ClassConstructors != null && ClassConstructors.Count() > 0) { this.ClassConstructors[0].Invoke(new object[3] { bFS, DestinationFileStream, false }); //new ar.Method(bFS, DestinationFileStream, false); } else { Console.WriteLine("Файлы поврежены. Неудалось загрузить из сбоки {0} тип {1}", this.AssemblyConstructorType.Module.FullyQualifiedName, this.AssemblyConstructorType.FullName); throw new Exception(); } DestinationFileStream.Close(); } bFS.Close(); } /// /// Старое чтение /// /* * using (System.IO.FileStream bFS = new System.IO.FileStream(System.Environment.CurrentDirectory + FileInfo.PathModifier(Path), System.IO.FileMode.Open, System.IO.FileAccess.Write)) * { * using (System.IO.BinaryReader brFS = new System.IO.BinaryReader(new System.IO.FileStream(this.TemporaryFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))) * { * for (FileInfo.PosBuff = 0; FileInfo.PosBuff < FileInfo.FileLength; ++FileInfo.PosBuff) * { * this.ByteBuff = brFS.ReadByte(); * bFS.WriteByte(this.ByteBuff); * } * brFS.Close(); * } * bFS.Close(); * } */ if (System.IO.File.Exists(this.TemporaryFile)) { System.IO.File.Delete(this.TemporaryFile); } } else { FileInfo.LogFileHandle.Write("Файл " + System.Environment.CurrentDirectory + FileInfo.PathModifier(Path) + " поврежден при записи и не был разархивирован!"); Console.WriteLine("Файл {0} поврежден при записи и не был разархивирован!", System.Environment.CurrentDirectory + FileInfo.PathModifier(Path)); return; } } } catch { FileInfo.LogFileHandle.Write("Программа не может получить доступ к " + System.Environment.CurrentDirectory + FileInfo.PathModifier(Path)); Console.WriteLine("Программа не может получить доступ к {0}", System.Environment.CurrentDirectory + FileInfo.PathModifier(Path)); FileInfo.NotReadFile = true; //BinFileReader.BaseStream.Position += FileInfo.FileLength; } } /// Запись атрибутов if (!FileInfo.NotReadFile) { FileInfo.WriteAttribs(System.Environment.CurrentDirectory + FileInfo.PathModifier(Path)); } }while (BinFileReader.BaseStream.Position < BinFileReader.BaseStream.Length); /*if (BinFileReader.BaseStream.Position < BinFileReader.BaseStream.Length) * { * MakeFileFromArchive(Path, BinFileReader, FileInfo); * }*/ }
/// <summary> /// Сжимает папку/файл /// </summary> /// <param name="path"> Путь к файлу/папке, который[ую] необходимо сжать </param> /// <param name="BinFileWriter"> Поток записи в архив </param> private void Compress(string path, System.IO.BinaryWriter BinFileWriter) { /// /// Если архив /// if (path == this.ArchPath || path == (AppDomain.CurrentDomain.BaseDirectory + this.ArchPath)) { Console.WriteLine("---------------------\n| Except\n---------------------\n|Невозможно считать файл, в котором формируется архив\n|Файл записан не будет\n|Путь к файлу: {0}\n---------------------", path); return; } this.NotTempFile = false; if (System.IO.File.Exists(path)) { try { this.TemporaryFile = System.IO.Path.GetTempFileName(); this.StreamOfBaseFile = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); ++StreamOfBaseFile.Position; this.TemporaryFileStream = System.IO.File.Create(this.TemporaryFile); this.NeededAssembly = System.Environment.CurrentDirectory + System.IO.Path.DirectorySeparatorChar + AssemblysFolderName + System.IO.Path.DirectorySeparatorChar + @"M" + this.MethodIndex + @".dll"; try { if (System.IO.File.Exists(this.NeededAssembly)) { this.MethodAssembly = System.Reflection.Assembly.LoadFile(this.NeededAssembly); } else { Console.WriteLine("Сборка отсутствуeт: {1} Переустановите программу!", this.NeededAssembly); throw new Exception(); } } catch { Console.WriteLine("Сборка {0} повреждена. Загрузите ее заново!", this.NeededAssembly); throw new Exception(); } /// TDOD: Проанализировать возможность выполнения через System.AppDomain.CurrentDomain.ExecuteAssembly /// Без загрузки в текуший домен /// ///--------------------------------------------------- /// /// Вытаскивание конструкторов из класса и вызов 0ого. /// TODO: Конкретизировать выбор конструктора /// this.AssemblyConstructorType = this.MethodAssembly.GetType("Method.Method"); this.ClassConstructors = this.AssemblyConstructorType.GetConstructors(); //System.Reflection.ConstructorInfo ci = ti.GetConstructor(new Type[1] { tis/*this.TemporaryFile.GetType()*//*, true.GetType()*/}); if (this.ClassConstructors != null && ClassConstructors.Count() > 0) { this.ClassConstructors[0].Invoke(new object[3] { this.StreamOfBaseFile, this.TemporaryFileStream, true }); //new Method(this.StreamOfBaseFile, this.TemporaryFileStream, true); } else { Console.WriteLine("Файлы поврежены. Неудалось загрузить из сбоки {0} тип {1}", this.AssemblyConstructorType.Module.FullyQualifiedName, this.AssemblyConstructorType.FullName); throw new Exception(); } ///--------------------------------------------------- /// Проверка изменения пути к файлу и удаление отосланного, если он был переписан в новый /// if (this.TemporaryFileStream.Length == 0) { if (System.IO.File.Exists(this.TemporaryFile)) { this.TemporaryFileStream.Close(); System.IO.File.Delete(this.TemporaryFile); this.NotTempFile = true; } this.TemporaryFile = path; } this.TemporaryFileStream.Close(); this.StreamOfBaseFile.Close(); this.StreamOfBaseFile = new System.IO.FileStream(this.TemporaryFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); } catch (System.UnauthorizedAccessException)//(System.IO.IOException) { Console.WriteLine("Невозможно получить доступ к файлу: " + path); Console.WriteLine("Продолжить работу с ошибкой [y/n]"); var KeyPressed = Console.ReadKey().KeyChar; if (KeyPressed == 'y' || KeyPressed == 'Y') { return; } else { BinFileWriter.BaseStream.Close(); BinFileWriter.Close(); throw new Exception("Программа остановлена по запросу пользователя"); } } MakeFileInArchive(path, this.TemporaryFile, BinFileWriter); /// <summary> /// Чтение файла из потока StreamOfBaseFile /// TODO: Ускорить чтение, путем чтения не одного байта, а набора байтов сразу /// Количество выделяемых байт под буффер должно определяться автоматически, /// в зависимости от количества доступной оперативной памяти /// </summary> for (this.Byte_Buff = 0; this.StreamOfBaseFile.Position < this.StreamOfBaseFile.Length;) { this.Byte_Buff = (byte)this.StreamOfBaseFile.ReadByte(); BinFileWriter.Write(this.Byte_Buff); } this.StreamOfBaseFile.Close(); /// /// Удаление временного файла /// if (System.IO.File.Exists(this.TemporaryFile) && !this.NotTempFile) { System.IO.File.Delete(this.TemporaryFile); } } else { MakeFileInArchive(path, this.TemporaryFile, BinFileWriter); //MakeFileInArchive(this.TemporaryFile, BinFileWriter); /// /// По идее кушает памяти больше чем ниже преведенный фрагмент /// //new Archive_creator(path, BinFileWriter, this.FilesPath, this.TemporaryFolder, this.ArchPath, this.MethodIndex); /// <summary> /// Для предотвращения вылета при отказе в доступе к папке /// </summary> try { foreach (var npath in System.IO.Directory.EnumerateFileSystemEntries(path)) { Compress(npath, BinFileWriter); } } catch (System.Security.SecurityException) { Console.WriteLine("Except: Отказанно в доступе к папке: {0}", path); } } }