public void unzipFile(string archive_name) { // Open an existing zip file for reading ZipStorer zip = ZipStorer.Open(archive_name, FileAccess.Read); string local_filename = null; if (Path.GetExtension(archive_name) == ".zip") // remove .zip extention { local_filename = Path.GetFileName(archive_name.Substring(0, archive_name.Length - 4)); } // Read the central directory collection List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); // Look for the desired file foreach (ZipStorer.ZipFileEntry entry in dir) { string zippedFilename = Path.GetFileName(entry.FilenameInZip); //Console.WriteLine("Unzip zippedFilename: {0}", zippedFilename); //Console.WriteLine("Unzip local_file: {0}", local_filename); if (!zippedFilename.Equals(local_filename, StringComparison.InvariantCultureIgnoreCase)) { Console.WriteLine("Unzip skipping file: {0}", zippedFilename); continue; } zip.ExtractFile(entry, Path.Combine(Path.GetDirectoryName(archive_name), zippedFilename)); if (zippedFilename == CFG_FILENAME) { Console.WriteLine("Reloading config file ..."); loadConfigFile(); } } zip.Dispose(); }
/// <summary> /// обработка сообщения DELETE /// </summary> /// <param name="iU"></param> /// <param name="data"></param> private void DeleteFile(byte[] data) { string name = GetPasString(data, 7 * 2); if (Login != Access.GetUser(name)) { Console.WriteLine("{0}: Неудачная попытка удалить файл {1}", Login, name); ConLog.WriteLine("{0}: Неудачная попытка удалить {1}", Login, name); SendResponse(CryWr, "ERROR"); return; } //////////////////////// byte[] Key = new byte[0x20]; byte[] IV = new byte[0x10]; for (int i = 0; i < 0x20; i++) { Key[i] = data[i + 7 * 2 + 1 + name.Length * 2]; } for (int i = 0; i < 0x10; i++) { IV[i] = data[i + 7 * 2 + 1 + name.Length * 2 + 0x20]; } byte[] DataFile = new byte[2 * 1048576]; //bool DecryptOk = false; //////////////////////////// разархивирование try { using (MemoryStream msResult = new MemoryStream()) { using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = Key; rijAlg.IV = IV; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); ZipStorer zip = ZipStorer.Open(name + ".zip", FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); Stream zs = zip.ExtractStream(dir[0]); using (CryptoStream csDecrypt = new CryptoStream(zs, decryptor, CryptoStreamMode.Read)) { //int iRead; zip.ExtractReadInNull(dir[0], csDecrypt, 0, (int)dir[0].FileSize); /*do * { * msResult.Seek(0, SeekOrigin.Begin); * iRead = zip.ExtractRead(dir[0], csDecrypt, msResult, 0, 2 * 1048576); * } while (iRead == 1048576 * 2); */ } zs.Dispose(); zip.Dispose(); } msResult.Close(); } } catch (Exception) { Console.WriteLine("{0}: Неудачная попытка удалить файл {1}", Login, name); ConLog.WriteLine("{0}: Неудачная попытка удалить {1}", Login, name); SendResponse(CryWr, "ERROR"); return; } DataFile = null; //////////////////////// if (Access.DeleteFile(name)) { File.Delete(name + ".zip"); } else { Console.WriteLine("{0}: Неудачная попытка удалить файл {1}", Login, name); ConLog.WriteLine("{0}: Неудачная попытка удалить {1}", Login, name); SendResponse(CryWr, "ERROR"); return; } Console.WriteLine("{0}: удалён файл {1}", Login, name); ConLog.WriteLine("{0}: удалён файл {1}", Login, name); SendResponse(CryWr, "OK"); }
public static string unzipEPubAndGetOpfPath(string EPUBFullPath) { //if (RequestCancellation) return; string parentDirectoryFullPath = Directory.GetParent(EPUBFullPath).ToString(); string unzipDirectory = Path.Combine( parentDirectoryFullPath, Path.GetFileNameWithoutExtension(EPUBFullPath) + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); ZipStorer zip = ZipStorer.Open(File.OpenRead(EPUBFullPath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { //if (RequestCancellation) return; //reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; if (Path.GetExtension(unzippedFilePath).ToLower() == ".opf" || Path.GetExtension(unzippedFilePath).ToLower() == ".xml") { string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } } zip.Dispose(); string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); string opfFullPath = null; if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); foreach (FileInfo fileInfo in opfFiles) { opfFullPath = Path.Combine(unzipDirectory, fileInfo.FullName); //m_OPF_ContainerRelativePath = null; break; } } else { //parseContainerXML(containerPath); XmlDocument containerDoc = XmlReaderWriterHelper.ParseXmlDocument(containerPath, false, false); XmlNode rootFileNode = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(containerDoc, true, @"rootfile", containerDoc.DocumentElement.NamespaceURI); #if DEBUG XmlNode mediaTypeAttr = rootFileNode.Attributes.GetNamedItem(@"media-type"); DebugFix.Assert(mediaTypeAttr != null && mediaTypeAttr.Value == @"application/oebps-package+xml"); #endif XmlNode fullPathAttr = rootFileNode.Attributes.GetNamedItem(@"full-path"); string rootDirectory = Path.GetDirectoryName(containerPath); rootDirectory = rootDirectory.Substring(0, rootDirectory.IndexOf(@"META-INF")); string OPF_ContainerRelativePath = FileDataProvider.UriDecode(fullPathAttr.Value); if (OPF_ContainerRelativePath.StartsWith(@"./")) { OPF_ContainerRelativePath = OPF_ContainerRelativePath.Substring(2); } opfFullPath = Path.Combine(rootDirectory, OPF_ContainerRelativePath.Replace('/', '\\')); } return(opfFullPath); }
private void unzipEPubAndParseOpf() { if (RequestCancellation) { return; } /*string directoryName = Path.GetTempPath(); * if (!directoryName.EndsWith("" + Path.DirectorySeparatorChar)) * { * directoryName += Path.DirectorySeparatorChar; * }*/ string unzipDirectory = Path.Combine( Path.GetDirectoryName(m_Book_FilePath), //m_outDirectory, //FileDataProvider.EliminateForbiddenFileNameCharacters(m_Book_FilePath) //m_Book_FilePath.Replace('.', '_') m_Book_FilePath + "_ZIP" ); FileDataProvider.TryDeleteDirectory(unzipDirectory, true); #if ENABLE_SHARPZIP ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(m_Book_FilePath)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { if (RequestCancellation) { return; } string zipEntryName = Path.GetFileName(zipEntry.Name); if (!String.IsNullOrEmpty(zipEntryName)) // || zipEntryName.IndexOf(".ini") >= 0 { // string unzippedFilePath = Path.Combine(unzipDirectory, zipEntryName); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + zipEntry.Name; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } FileStream fileStream = File.Create(unzippedFilePath); //byte[] data = new byte[2 * 1024]; // 2 KB buffer //int bytesRead = 0; try { const uint BUFFER_SIZE = 1024 * 2; // 2 KB MAX BUFFER StreamUtils.Copy(zipInputStream, 0, fileStream, BUFFER_SIZE); //while ((bytesRead = zipInputStream.Read(data, 0, data.Length)) > 0) //{ // fileStream.Write(data, 0, bytesRead); //} } finally { fileStream.Close(); } } } zipInputStream.Close(); #else //ENABLE_SHARPZIP ZipStorer zip = ZipStorer.Open(File.OpenRead(m_Book_FilePath), FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); foreach (ZipStorer.ZipFileEntry entry in dir) { if (RequestCancellation) { return; } reportProgress_Throttle(-1, String.Format(UrakawaSDK_daisy_Lang.Unzipping, entry.FilenameInZip)); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + entry.FilenameInZip; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { FileDataProvider.CreateDirectory(unzippedFileDir); } zip.ExtractFile(entry, unzippedFilePath); } //zip.Close(); zip.Dispose(); #endif //ENABLE_SHARPZIP string containerPath = Path.Combine(unzipDirectory, @"META-INF" + Path.DirectorySeparatorChar + @"container.xml"); if (!File.Exists(containerPath)) { #if DEBUG Debugger.Break(); #endif DirectoryInfo dirInfo = new DirectoryInfo(unzipDirectory); #if NET40 IEnumerable <FileInfo> opfFiles = dirInfo.EnumerateFiles("*.opf", SearchOption.AllDirectories); #else FileInfo[] opfFiles = dirInfo.GetFiles("*.opf", SearchOption.AllDirectories); #endif // string[] fileNames = Directory.GetFiles(unzipDirectory, "*.opf", //#if NET40 // SearchOption.AllDirectories //#endif // ); foreach (FileInfo fileInfo in opfFiles) { if (RequestCancellation) { return; } m_Book_FilePath = Path.Combine(unzipDirectory, fileInfo.FullName); m_OPF_ContainerRelativePath = null; openAndParseOPF(m_Book_FilePath); break; } } else { parseContainerXML(containerPath); } // string opfPath = ""; // string parentDir = Path.GetDirectoryName(opfPath); // while (!string.IsNullOrEmpty(parentDir)) // { // DirectoryInfo dirInfo = new DirectoryInfo(parentDir); // DirectoryInfo[] metaInfDirs = dirInfo.GetDirectories(@"META-INF", SearchOption.TopDirectoryOnly); // if (RequestCancellation) return; // foreach (DirectoryInfo dirInfo in metaInfDirs) // { // string containerPath = Path.Combine(parentDir, dirInfo.FullName + Path.DirectorySeparatorChar + @"container.xml"); // if (!File.Exists(containerPath)) // { //#if DEBUG // Debugger.Break(); //#endif // } // else // { // if (!parseContainerXML(containerPath)) // { // openAndParseOPF(opfPath); // } // } // break; // } // DirectoryInfo parentDirInfo = dirInfo.Parent; // if (parentDirInfo != null) // { // parentDir = parentDirInfo.FullName; // } // else // { // parentDir = null; // } // } // // final fallback // openAndParseOPF(opfPath); }
/// <summary> /// Запрашивает архив с сервера /// </summary> /// <param name="path">путь, куда будет распакован и расшифрован файл</param> /// <param name="name">имя файла</param> public void SRVGetFile(FrmWait frmWait, string path, string name) { if (MyKey == null) { MessageBox.Show("Введите пароль"); return; } // сразу проверим, сможем ли мы записать в файл данные, иначе скачивать бессмысленно if (File.Exists(path)) { if ((File.GetAttributes(path) != FileAttributes.Normal) && (File.GetAttributes(path) != FileAttributes.Archive)) { MessageBox.Show("Невозможно перезаписать файл"); return; } } SendResponse("GET ", name); while (lastRec == null) { Thread.Sleep(100); } int tmpSize = 10 * 2; //берём в строку только первые 10 символов if (tmpSize > lastRec.Length) { tmpSize = lastRec.Length; //или сколько там этих символов есть в сообщении } string tmpStr = Encoding.Unicode.GetString(lastRec, 0, tmpSize); string command = tmpStr.Split(' ')[0]; int posData; int sizeFile; byte[] ThisKey; if (command == "FILE") { ThisKey = MyKey; sizeFile = ToInt(lastRec, 5 * 2); //размер файла posData = 5 * 2 + 4; } else if (command == "FILEPSWD") { ThisKey = new byte[0x20]; for (int i = 0; i < 0x20; i++) { ThisKey[i] = lastRec[9 * 2 + i]; } sizeFile = ToInt(lastRec, 9 * 2 + 0x20); //размер файла posData = 9 * 2 + 4 + 0x20; } else { frmWait.End(); lastRec = null; MessageBox.Show("Не удалось скачать файл"); return; } try { using (FileStream inFS = File.Create(path)) { using (RijndaelManaged rijAlg = new RijndaelManaged()) { rijAlg.Key = ThisKey; rijAlg.IV = MyIV; ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV); using (CryptoStream csDecrypt = new CryptoStream(inFS, decryptor, CryptoStreamMode.Write)) { MemoryStream msInp = new MemoryStream(lastRec, posData, lastRec.Length - posData); FileStream fsTemp = File.Create(path + ".tmp"); byte[] bfsize = new byte[4]; CryRd.Read(bfsize, 0, 4); int allFileSize = ToInt(bfsize); int rec = 0; while (rec < allFileSize) { int bufSize = Math.Min(1048576, allFileSize - rec); byte[] bufFile = new byte[bufSize]; CryRd.Read(bufFile, 0, bufSize); fsTemp.Write(bufFile, 0, bufSize); rec += bufSize; } fsTemp.Seek(0, SeekOrigin.Begin); msInp.Seek(0, SeekOrigin.Begin); ZipStorer zip = ZipStorer.Open(fsTemp, FileAccess.Read); List <ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir(); zip.ExtractFile(dir[0], csDecrypt); zip.Close(); zip.Dispose(); fsTemp.Close(); File.Delete(path + ".tmp"); msInp.Dispose(); } } } } catch (Exception e) { frmWait.End(); lastRec = null; GC.Collect(); MessageBox.Show(e.Message); return; } lastRec = null; GC.Collect(); frmWait.End(); MessageBox.Show("Файл " + name + " успешно скачан"); }