Создать архив с паролем - C#
Формулировка задачи:
Добрый вечер, я пишу архиватор, и хочу сделать так чтобы на него можно было устанавливать пароль, а именно : написать пароль в textBox, и при нажатии на button создавался архив с данным паролем, как это лучше реализовать?
Решение задачи: «Создать архив с паролем»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Windows.Forms.VisualStyles;
using Ionic.Zip;
namespace ListView
{
public partial class Form1 : Form
{
public FolderBrowserDialog SaveDialog;
public OpenFileDialog OpenFiles;
public SaveFileDialog SaveFile;
public ZipFile zip;
string FPath;
string backPath;
public List<string> filess = new List<string>();
public string Archive;
List<string> ls = new List<string>();
public Form1()
{
InitializeComponent();
listView2.View = View.Details;
listView2.GridLines = true;
listView2.CheckBoxes = true;
listView2.Columns.Add("Name", -2, HorizontalAlignment.Left);
listView2.Columns.Add("Size, kb", -2, HorizontalAlignment.Left);
listView2.Columns.Add("Type", -2, HorizontalAlignment.Left);
}
void GetLocDir()
{
listView1.Items.Clear();
textBox1.Text = "Мой компьютер";
String[] LogicalDrives = Environment.GetLogicalDrives();
foreach (string s in LogicalDrives)
{
listView1.Items.Add(s, 1);
ls.Add(s);
}
}
void GetFiles()
{
listView1.BeginUpdate();
try
{
string[] dirs = Directory.GetDirectories(FPath);
ls.Clear();
try
{
DirectoryInfo dInfo = new DirectoryInfo(FPath);
backPath = dInfo.Parent.FullName;
}
catch { }
listView1.Items.Clear();
foreach (string s in dirs)
{
string dirname = System.IO.Path.GetFileName(s);
listView1.Items.Add(dirname, 1);
ls.Add(s);
}
string[] files = Directory.GetFiles(FPath);
foreach (string s in files)
{
string filename = System.IO.Path.GetFileName(s);
listView1.Items.Add(filename, 0);
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
listView1.EndUpdate();
}
private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
listView2.Items.Clear();
foreach (string file in Directory.GetFiles(fbd.SelectedPath))
{
ListViewItem item1 = new ListViewItem(Path.GetFileName(file));
item1.SubItems.Add((Math.Round(new FileInfo(file).Length / 1024.0, 2)).ToString());
Win32API.SHFILEINFO info = new Win32API.SHFILEINFO();
uint dwFileAttributes = Win32API.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL;
uint uFlags = (uint)(Win32API.SHGFI.SHGFI_TYPENAME | Win32API.SHGFI.SHGFI_USEFILEATTRIBUTES);
Win32API.SHGetFileInfo(file, dwFileAttributes, ref info, (uint)Marshal.SizeOf(info), uFlags);
item1.SubItems.Add(info.szTypeName);
item1.Checked = true;
listView2.Items.Add(item1);
}
for (int i = 0; i < listView2.Columns.Count; i++)
listView2.AutoResizeColumn(i, ColumnHeaderAutoResizeStyle.ColumnContent);
}
}
private void listView1_ItemActivate(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count == 0)
return;
ListViewItem item = listView1.SelectedItems[0];
if (item.ImageIndex == 1)
{
string it = item.Text;
string title = "";
foreach (string s in ls)
{
try
{
if (s.Substring(s.Length - it.Length, it.Length) == it)
{
FPath = s;
title = s;
}
}
catch { }
}
try
{
string[] dirs = Directory.GetDirectories(FPath);
textBox1.Text = title;
GetFiles();
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
else if (item.ImageIndex == 0)
{
string start = textBox1.Text + "" + item.Text;
System.Diagnostics.Process.Start(start);
}
}
private void button1_Click(object sender, EventArgs e)
{
bool b = false;
String[] LogicalDrives = Environment.GetLogicalDrives();
foreach (string s in LogicalDrives)
{
if (backPath == s && FPath == s) b = true;
}
if (backPath != null && !b)
{
this.Text = backPath;
FPath = backPath;
GetFiles();
}
else
{
GetLocDir();
}
}
private void Form1_Load(object sender, EventArgs e)
{
GetLocDir();
}
FolderBrowserDialog bd = new FolderBrowserDialog();
private void button2_Click(object sender, EventArgs e)
{
OpenFiles = new OpenFileDialog();
OpenFiles.Title = "Выберите файлы, которые необходимо заархивировать";
if (OpenFiles.ShowDialog() == DialogResult.OK)
{
filess.AddRange(OpenFiles.FileNames);
}
try
{
string path = "";
SaveFile = new SaveFileDialog();
SaveFile.Title = "Сохранение архива";
SaveFile.FileName = "Archive (" + DateTime.Now.ToShortDateString() + ")";
SaveFile.Filter = "Файл ZIP|*.zip";
if (SaveFile.ShowDialog() == DialogResult.OK)
{
path = SaveFile.FileName;
}
else throw new Exception("Не выбрано место для сохранения архива!");
using (zip = new ZipFile(path, Encoding.UTF8))
{
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
zip.TempFileFolder = Path.GetTempPath();
zip.Password = "пароль";
foreach (string f in filess)
{
zip.AddFile(f, "");
}
zip.Save();
zip = null;
}
}
catch (Exception)
{
MessageBox.Show("Вы не выбрали файл.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("Данные успешно сохранены", "Инфо", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
private void button3_Click(object sender, EventArgs e)
{
OpenFiles = new OpenFileDialog();
OpenFiles.Title = "Выберите архив, который необходимо разархивировать";
if (OpenFiles.ShowDialog() == DialogResult.OK)
{
Archive = OpenFiles.FileName;
}
string path = "";
SaveDialog = new FolderBrowserDialog();
SaveDialog.Description = "Выберите папку для разархивации";
if (SaveDialog.ShowDialog() == DialogResult.OK)
{
path = SaveDialog.SelectedPath;
}
else throw new Exception("Не выбрано место для разархивации архива!");
using (zip = new ZipFile(Archive, Encoding.UTF8))
{
zip.TempFileFolder = System.IO.Path.GetTempPath();
zip.ExtractAll(path, ExtractExistingFileAction.OverwriteSilently);
zip = null;
}
MessageBox.Show("Данные успешно извлечены", "Инфо", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
private void button4_Click(object sender, EventArgs e)
{
ListViewItem item = listView1.SelectedItems[0];
listView1.Items.Remove(item);
}
private void выходToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void добавитьАрхивToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 f3 = new Form3();
f3.Show();
}
private void извлечьАрхивToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFiles = new OpenFileDialog();
OpenFiles.Title = "Выберите архив, который необходимо разархивировать";
if (OpenFiles.ShowDialog() == DialogResult.OK)
{
Archive = OpenFiles.FileName;
}
string path = "";
SaveDialog = new FolderBrowserDialog();
SaveDialog.Description = "Выберите папку для разархивации";
if (SaveDialog.ShowDialog() == DialogResult.OK)
{
path = SaveDialog.SelectedPath;
}
else throw new Exception("Не выбрано место для разархивации архива!");
using (zip = new ZipFile(Archive, Encoding.UTF8))
{
zip.TempFileFolder = System.IO.Path.GetTempPath();
zip.ExtractAll(path, ExtractExistingFileAction.OverwriteSilently);
zip = null;
}
MessageBox.Show("Данные успешно извлечены", "Инфо", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}