
3D-маньяк
   
Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск
Репутация: 110 Всего: 232
|
Вот пример кода из одного старого проекта, думаю можно разобраться: | Код | static void SaveTo(string outPath) { try { // пакуем все файлы в архив FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.Write); ZipOutputStream zos = new ZipOutputStream(fs); zos.SetLevel(9);
// имена файлов в русской кодировке пишем в отдельный .txt-файл string fileNames = string.Empty; int iFile = 0;
DirectoryInfo di = new DirectoryInfo(Program.ArchiveDir); foreach (DirectoryInfo ddi in di.GetDirectories()) { foreach (DirectoryInfo dddi in ddi.GetDirectories()) { foreach (FileInfo fi in dddi.GetFiles()) { byte[] content = new byte[0]; try { FileStream docFile = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read); content = new byte[docFile.Length]; docFile.Read(content, (int)0, (int)docFile.Length); docFile.Close(); } catch { DialogResult dr2 = MessageBox.Show(MainForm.Instance, "Файл \'" + fi.Name + "\' невозможно прочитать, скорее всего он открыт в Microsoft Word\nЗакройте все открытые окна Word и повторите попытку\n\nНажмите \'Пропустить\', чтобы проигнорировать этот файл и продолжить\nНажмите \'Отмена\', чтобы отменить сохранение архива.", "Ошибка", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if (dr2 == DialogResult.Cancel) return; else continue; }
zos.PutNextEntry(new ZipEntry(iFile.ToString() + ".doc")); zos.Write(content, 0, content.Length); iFile++;
string russianFileName = ddi.Name + "/" + dddi.Name + "/" + fi.Name; if (fileNames != string.Empty) fileNames += Environment.NewLine; fileNames += russianFileName; } } }
zos.PutNextEntry(new ZipEntry("RussianFileNames.txt")); StreamWriter writer = new StreamWriter(zos, Encoding.UTF8); writer.Write(fileNames); writer.Flush();
zos.Finish(); zos.Close();
MessageBox.Show(MainForm.Instance, "Архив был успешно сохранён в файл:\n" + outPath, "Сохранение завершено", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(MainForm.Instance, "Не удалось сохранить архив, по причине:\n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void RestoreFrom(string inPath) { try { ZipEntry ze;
// читаем имена в русской кодировке string fileNames = string.Empty; FileStream fs_tmp = new FileStream(inPath, FileMode.Open, FileAccess.Read); ZipInputStream zis_tmp = new ZipInputStream(fs_tmp); try { while ((ze = zis_tmp.GetNextEntry()) != null) { if (ze.Name == "RussianFileNames.txt") { byte[] buffer = new byte[ze.Size]; int pos = 0; int bytesRead; do { bytesRead = zis_tmp.Read(buffer, pos, buffer.Length); pos += bytesRead; } while (bytesRead > 0);
MemoryStream ms = new MemoryStream(buffer); fileNames = new StreamReader(ms, Encoding.UTF8).ReadToEnd(); } } if (fileNames == string.Empty) { MessageBox.Show(MainForm.Instance, "Указанный файл не содержит архива", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } finally { zis_tmp.Close(); }
// распаковываем файлы, заменяя старые string[] afileNames = fileNames.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); FileStream fs = new FileStream(inPath, FileMode.Open, FileAccess.Read); ZipInputStream zis = new ZipInputStream(fs); while ((ze = zis.GetNextEntry()) != null) { try { int iFile = int.Parse(ze.Name.Substring(0, ze.Name.Length - 4)); string realFileName = afileNames[iFile]; string[] segs = realFileName.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); string path = Path.Combine(Program.ArchiveDir, segs[0]); if (!Directory.Exists(path)) Directory.CreateDirectory(path); path = Path.Combine(path, segs[1]); if (!Directory.Exists(path)) Directory.CreateDirectory(path); path = Path.Combine(path, segs[2]);
byte[] buffer = new byte[ze.Size]; int bytesRead = 0; int pos = 0; do { bytesRead = zis.Read(buffer, pos, buffer.Length); pos += bytesRead; } while (bytesRead > 0);
FileStream fsOut = new FileStream(path, FileMode.Create, FileAccess.Write); fsOut.Write(buffer, 0, buffer.Length); fsOut.Close(); } catch { continue; } }
zis.Close();
MessageBox.Show(MainForm.Instance, "Архив был успешно восстановлен из файла:\n" + inPath, "Восстановление завершено", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(MainForm.Instance, "Не удалось восстановить архив, по причине:\n" + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
|
З.Ы. SharpZipLib не поддерживает кодировку имён файлов в юникоде, пришлось отдельным файлом сохранять имена файлов в архиве.
|