C#压缩、解压缩文件(夹)(rar、zip)
主要是使用Rar.exe压缩解压文件(夹)(*.rar),另外还有使用SevenZipSharp.dll、zLib1.dll、7z.dll压缩解压文件(夹)(*.zip)。需要注意的几点如下:
1、注意Rar.exe软件存放的位置,此次放在了Debug目录下
2、SevenZipSharp.dll、zLib1.dll、7z.dll必须同时存在,否则常报“加载7z.dll错误”,项目引用时,只引用SevenZipSharp.dll即可
3、另外找不到7z.dll文件也会报错,测试时发现只用@"..\..\dll\7z.dll";相对路径时,路径是变化的,故此处才用了string libPath = System.AppDomain.CurrentDomain.BaseDirectory + @"..\..\dll\7z.dll";
SevenZip.SevenZipCompressor.SetLibraryPath(libPath);
。
。
。
具体代码如下:
Enums.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompressProj
{
/// <summary>
/// 执行压缩命令结果
/// </summary>
public enum CompressResults
{
Success,
SourceObjectNotExist,
UnKnown
}
/// <summary>
/// 执行解压缩命令结果
/// </summary>
public enum UnCompressResults
{
Success,
SourceObjectNotExist,
PasswordError,
UnKnown
}
/// <summary>
/// 进程运行结果
/// </summary>
public enum ProcessResults
{
Success,
Failed
}
}

CommonFunctions.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompressProj
{
class CommonFunctions
{
#region 单例模式
private static CommonFunctions uniqueInstance;
private static object _lock = new object();
private CommonFunctions() { }
public static CommonFunctions getInstance()
{
if (null == uniqueInstance) //确认要实例化后再进行加锁,降低加锁的性能消耗。
{
lock (_lock)
{
if (null == uniqueInstance)
{
uniqueInstance = new CommonFunctions();
}
}
}
return uniqueInstance;
}
#endregion
#region 进程
/// <summary>
/// 另起一进程执行命令
/// </summary>
/// <param name="exe">可执行程序(路径+名)</param>
/// <param name="commandInfo">执行命令</param>
/// <param name="workingDir">执行所在初始目录</param>
/// <param name="processWindowStyle">进程窗口样式</param>
/// <param name="isUseShellExe">Shell启动程序</param>
public void ExecuteProcess(string exe, string commandInfo, string workingDir = "", ProcessWindowStyle processWindowStyle = ProcessWindowStyle.Hidden,bool isUseShellExe = false)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = exe;
startInfo.Arguments = commandInfo;
startInfo.WindowStyle = processWindowStyle;
startInfo.UseShellExecute = isUseShellExe;
if (!string.IsNullOrWhiteSpace(workingDir))
{
startInfo.WorkingDirectory = workingDir;
}
ExecuteProcess(startInfo);
}
/// <summary>
/// 直接另启动一个进程
/// </summary>
/// <param name="startInfo">启动进程时使用的一组值</param>
public void ExecuteProcess(ProcessStartInfo startInfo)
{
try
{
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Close();
process.Dispose();
}
catch(Exception ex)
{
throw new Exception("进程执行失败:\n\r" + startInfo.FileName + "\n\r" + ex.Message);
}
}
/// <summary>
/// 去掉文件夹或文件的只读属性
/// </summary>
/// <param name="objectPathName">文件夹或文件全路径</param>
public void Attribute2Normal(string objectPathName)
{
if (true == Directory.Exists(objectPathName))
{
System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(objectPathName);
directoryInfo.Attributes = FileAttributes.Normal;
}
else
{
File.SetAttributes(objectPathName,FileAttributes.Normal);
}
}
#endregion
}
}

RarOperate.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CompressProj
{
class RarOperate
{
private CommonFunctions commFuncs = CommonFunctions.getInstance();
#region 单例模式
private static RarOperate uniqueInstance;
private static object _lock = new object();
private RarOperate() { }
public static RarOperate getInstance()
{
if (null == uniqueInstance) //确认要实例化后再进行加锁,降低加锁的性能消耗。
{
lock (_lock)
{
if (null == uniqueInstance)
{
uniqueInstance = new RarOperate();
}
}
}
return uniqueInstance;
}
#endregion
#region 压缩
/// <summary>
/// 使用Rar.exe压缩对象
/// </summary>
/// <param name="rarRunPathName">Rar.exe路径+对象名</param>
/// <param name="objectPathName">被压缩对象路径+对象名</param>
/// <param name="objectRarPathName">对象压缩后路径+对象名</param>
/// <returns></returns>
public CompressResults CompressObject(string rarRunPathName, string objectPathName, string objectRarPathName,string password)
{
try
{
//被压缩对象是否存在
int beforeObjectNameIndex = objectPathName.LastIndexOf('\\');
string objectPath = objectPathName.Substring(0, beforeObjectNameIndex);
//System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(objectPathName);
if (Directory.Exists(objectPathName)/*directoryInfo.Exists*/ == false && System.IO.File.Exists(objectPathName) == false)
{
return CompressResults.SourceObjectNotExist;
}
//将对应字符串转换为命令字符串
string rarCommand = "\"" + rarRunPathName + "\"";
string objectPathNameCommand = "\"" + objectPathName + "\"";
int beforeObjectRarNameIndex = objectRarPathName.LastIndexOf('\\');
int objectRarNameIndex = beforeObjectRarNameIndex + 1;
string objectRarName = objectRarPathName.Substring(objectRarNameIndex);
string rarNameCommand = "\"" + objectRarName + "\"";
string objectRarPath = objectRarPathName.Substring(0, beforeObjectRarNameIndex);
//目标目录、文件是否存在
if (System.IO.Directory.Exists(objectRarPath) == false)
{
System.IO.Directory.CreateDirectory(objectRarPath);
}
else if (System.IO.File.Exists(objectRarPathName) == true)
{
System.IO.File.Delete(objectRarPathName);
}
//Rar压缩命令
string commandInfo = "a " + rarNameCommand + " " + objectPathNameCommand + " -y -p" + password + " -ep1 -r -s- -rr ";
//另起一线程执行
commFuncs.ExecuteProcess(rarCommand, commandInfo, objectRarPath, ProcessWindowStyle.Hidden);
CompressRarTest(rarCommand, objectRarPathName, password);
CorrectConfusedRar(objectRarPathName);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return CompressResults.UnKnown;
}
return CompressResults.Success;
}
#endregion
#region 解压
/// <summary>
/// 解压:将文件解压到某个文件夹中。 注意:要对路径加上双引号,避免带空格的路径,在rar命令中失效
/// </summary>
/// <param name="rarRunPath">rar.exe的名称及路径</param>
/// <param name="fromRarPath">被解压的rar文件路径</param>
/// <param name="toRarPath">解压后的文件存放路径</param>
/// <returns></returns>
public UnCompressResults unCompressRAR(String rarRunPath, String objectRarPathName, String objectPath, string password)
{
try
{
bool isFileExist = File.Exists(objectRarPathName);
if (false == isFileExist)
{
MessageBox.Show("解压文件不存在!" + objectRarPathName);
return UnCompressResults.SourceObjectNotExist;
}
File.SetAttributes(objectRarPathName, FileAttributes.Normal); //去掉只读属性
if (Directory.Exists(objectPath) == false)
{
Directory.CreateDirectory(objectPath);
}
String rarCommand = "\"" + rarRunPath + "\"";
String objectPathCommand = "\"" + objectPath + "\\\"";
String commandInfo = "x \"" + objectRarPathName + "\" " + objectPath + " -y -p" + password;
commFuncs.ExecuteProcess(rarCommand, commandInfo, objectPath, ProcessWindowStyle.Hidden);
MessageBox.Show("解压缩成功!" + objectRarPathName);
return UnCompressResults.Success;
}
catch
{
MessageBox.Show( "解压缩失败!" + objectRarPathName);
return UnCompressResults.UnKnown;
}
}
#endregion
#region 进程
#endregion
#region 测试压缩文件
/// <summary>
/// 测试压缩后的文件是否正常。
/// </summary>
/// <param name="rarRunPath"></param>
/// <param name="rarFilePathName"></param>
public bool CompressRarTest(String rarRunPath, String rarFilePathName,string password)
{
bool isOk = false;
String commandInfo = "t -p" + password + " \"" + rarFilePathName + "\"";
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = rarRunPath;
startInfo.Arguments = commandInfo;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.CreateNoWindow = true;
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
StreamReader streamReader = process.StandardOutput;
process.WaitForExit();
if (streamReader.ReadToEnd().ToLower().IndexOf("error") >= 0)
{
MessageBox.Show("压缩文件已损坏!");
isOk = false;
}
else
{
MessageBox.Show("压缩文件良好!");
isOk = true;
}
process.Close();
process.Dispose();
return isOk;
}
/// <summary>
/// 混淆Rar
/// </summary>
/// <param name="objectRarPathName">rar路径+名</param>
/// <returns></returns>
public bool ConfusedRar(string objectRarPathName)
{
try
{
//混淆
System.IO.FileStream fs = new FileStream(objectRarPathName, FileMode.Open);
fs.WriteByte(0x53);
fs.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show("混淆Rar失败!" + ex.Message);
return false;
}
}
/// <summary>
/// 纠正混淆的Rar
/// </summary>
/// <param name="objectRarPathName">rar路径+名</param>
/// <returns></returns>
public bool CorrectConfusedRar(string objectRarPathName)
{
bool isCorrect = false;
try
{
//先判断一下待解压文件是否经过混淆
FileStream fsRar = new FileStream(objectRarPathName, FileMode.Open, FileAccess.Read);
int b = fsRar.ReadByte();
fsRar.Close();
if (b != 0x52) //R:0x52 原始开始值
{
string strTempFile = System.IO.Path.GetTempFileName();
File.Copy(objectRarPathName, strTempFile, true);
File.SetAttributes(strTempFile, FileAttributes.Normal); //去掉只读属性
FileStream fs = new FileStream(strTempFile, FileMode.Open);
fs.WriteByte(0x52);
fs.Close();
System.IO.File.Delete(objectRarPathName);
File.Copy(strTempFile, objectRarPathName, true);
}
isCorrect = true;
return isCorrect;
}
catch
{
MessageBox.Show("判断待解压文件是否经过混淆时出错!" + objectRarPathName);
return isCorrect;
}
}
#endregion
#region
#endregion
}
}

ZipOperate.cs
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
|
using SevenZip;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace CompressProj{ class ZipOperate { #region 单例模式 private static ZipOperate uniqueInstance; private static object _lock = new object(); private ZipOperate() { } public static ZipOperate getInstance() { if (null == uniqueInstance) //确认要实例化后再进行加锁,降低加锁的性能消耗。 { lock (_lock) { if (null == uniqueInstance) { uniqueInstance = new ZipOperate(); } } } return uniqueInstance; } #endregion #region 7zZip压缩、解压方法 /// <summary> /// 压缩文件 /// </summary> /// <param name="objectPathName">压缩对象(即可以是文件夹|也可以是文件)</param> /// <param name="objectZipPathName">保存压缩文件的路径</param> /// <param name="strPassword">加密码</param> /// 测试压缩文件夹:压缩文件(objectZipPathName)不能放在被压缩文件(objectPathName)内,否则报“文件夹被另一进程使用中”错误。 /// <returns></returns> public CompressResults Compress7zZip(String objectPathName, String objectZipPathName, String strPassword) { try { //http://sevenzipsharp.codeplex.com/releases/view/51254 下载sevenzipsharp.dll //SevenZipSharp.dll、zLib1.dll、7z.dll必须同时存在,否则常报“加载7z.dll错误” string libPath = System.AppDomain.CurrentDomain.BaseDirectory + @"..\..\dll\7z.dll"; SevenZip.SevenZipCompressor.SetLibraryPath(libPath); SevenZip.SevenZipCompressor sevenZipCompressor = new SevenZip.SevenZipCompressor(); sevenZipCompressor.CompressionLevel = SevenZip.CompressionLevel.Fast; sevenZipCompressor.ArchiveFormat = SevenZip.OutArchiveFormat.Zip; //被压缩对象是否存在 int beforeObjectNameIndex = objectPathName.LastIndexOf('\\'); string objectPath = objectPathName.Substring(0, beforeObjectNameIndex); //System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(objectPathName); if (Directory.Exists(objectPathName)/*directoryInfo.Exists*/ == false && System.IO.File.Exists(objectPathName) == false) { return CompressResults.SourceObjectNotExist; } int beforeObjectRarNameIndex = objectZipPathName.LastIndexOf('\\'); int objectRarNameIndex = beforeObjectRarNameIndex + 1; //string objectZipName = objectZipPathName.Substring(objectRarNameIndex); string objectZipPath = objectZipPathName.Substring(0, beforeObjectRarNameIndex); //目标目录、文件是否存在 if (System.IO.Directory.Exists(objectZipPath) == false) { System.IO.Directory.CreateDirectory(objectZipPath); } else if (System.IO.File.Exists(objectZipPathName) == true) { System.IO.File.Delete(objectZipPathName); } if (Directory.Exists(objectPathName)) //压缩对象是文件夹 { if (String.IsNullOrEmpty(strPassword)) { sevenZipCompressor.CompressDirectory(objectPathName, objectZipPathName); } else { sevenZipCompressor.CompressDirectory(objectPathName, objectZipPathName, strPassword); } } else //压缩对象是文件 无加密方式 { sevenZipCompressor.CompressFiles(objectZipPathName, objectPathName); } return CompressResults.Success; } catch(Exception ex) { MessageBox.Show("压缩文件失败!" + ex.Message); return CompressResults.UnKnown; } } /// <summary> /// 解压缩文件 /// </summary> /// <param name="zipFilePathName">zip文件具体路径+名</param> /// <param name="unCompressDir">解压路径</param> /// <param name="strPassword">解密码</param> /// <returns></returns> public UnCompressResults UnCompress7zZip(String zipFilePathName, String unCompressDir, String strPassword) { try { //SevenZipSharp.dll、zLib1.dll、7z.dll必须同时存在,否则常报“加载7z.dll错误”而项目引用时,只引用SevenZipSharp.dll就可以了 string libPath = System.AppDomain.CurrentDomain.BaseDirectory + @"..\..\dll\7z.dll"; SevenZip.SevenZipCompressor.SetLibraryPath(libPath); bool isFileExist = File.Exists(zipFilePathName); if (false == isFileExist) { MessageBox.Show("解压文件不存在!" + zipFilePathName); return UnCompressResults.SourceObjectNotExist; } File.SetAttributes(zipFilePathName, FileAttributes.Normal); //去掉只读属性 if (Directory.Exists(unCompressDir) == false) { Directory.CreateDirectory(unCompressDir); } SevenZip.SevenZipExtractor sevenZipExtractor; if (String.IsNullOrEmpty(strPassword)) { sevenZipExtractor = new SevenZip.SevenZipExtractor(zipFilePathName); } else { sevenZipExtractor = new SevenZip.SevenZipExtractor(zipFilePathName, strPassword); } sevenZipExtractor.ExtractArchive(unCompressDir); sevenZipExtractor.Dispose(); return UnCompressResults.Success; } catch(Exception ex) { MessageBox.Show("解压缩文件失败!" + ex.Message); return UnCompressResults.UnKnown; } } #endregion }} |
FileOperate.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CompressProj
{
class FileOperate
{
private RarOperate rarOperate = RarOperate.getInstance();
#region 单例模式
private static FileOperate uniqueInstance;
private static object _lock = new object();
private FileOperate() { }
public static FileOperate getInstance()
{
if (null == uniqueInstance) //确认要实例化后再进行加锁,降低加锁的性能消耗。
{
lock (_lock)
{
if (null == uniqueInstance)
{
uniqueInstance = new FileOperate();
}
}
}
return uniqueInstance;
}
#endregion
/// <summary>
/// 打开文件
/// </summary>
/// <param name="openFileDialog"></param>
/// <param name="filter"></param>
/// <param name="isReadOnly">是否另外开启一使用该文件进程,防止该文件被操作</param>
/// <returns></returns>
public string OpenFile(OpenFileDialog openFileDialog,string filter,string openFileDialogTitle = "压缩文件",bool isReadOnly = false)
{
string filePathName = string.Empty;
if (string.IsNullOrEmpty(filter))
{
filter = "AllFiles(*.*)|*.*"; //TXT(*.txt)|*.txt|Word(*.doc,*.docx)|*.doc;*.docx|图像文件(*.gif;*.jpg;*.jpeg;*.png;*.psd)|*.gif;*.jpg;*.jpeg;*.png;*.psd|
}
openFileDialog.Filter = filter;
DialogResult dResult = openFileDialog.ShowDialog();
if (dResult == DialogResult.OK)
{
string defaultExt = ".docx";
//string filter = string.Empty;
//openFileDialog.ReadOnlyChecked = isReadOnly;
openFileDialog.SupportMultiDottedExtensions = true;
openFileDialog.AutoUpgradeEnabled = true;
openFileDialog.AddExtension = true;
openFileDialog.CheckPathExists = true;
openFileDialog.CheckFileExists = true;
openFileDialog.DefaultExt = defaultExt;
openFileDialog.Multiselect = true;
openFileDialog.ShowReadOnly = true;
openFileDialog.Title = openFileDialogTitle;
openFileDialog.ValidateNames = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
//添加后界面没变化 Win7 + VS11
openFileDialog.ShowHelp = true;
filePathName = openFileDialog.FileName;
if (true == isReadOnly)
{
openFileDialog.OpenFile(); //打开只读文件,即开启一使用该文件进程,防止其他进程操作该文件
}
openFileDialog.Dispose();
}
return filePathName;
}
/// <summary>
/// 打开文件
/// </summary>
/// <param name="saveFileDialog"></param>
/// <param name="filter"></param>
/// <param name="isReadOnly"></param>
/// <returns></returns>
public string SaveFile(SaveFileDialog saveFileDialog, string filter,string saveFileDialogTitle = "保存文件", bool isReadOnly = false)
{
string filePathName = string.Empty;
if (string.IsNullOrEmpty(filter))
{
filter = "AllFiles(*.*)|*.*"; //TXT(*.txt)|*.txt|Word(*.doc,*.docx)|*.doc;*.docx|图像文件(*.gif;*.jpg;*.jpeg;*.png;*.psd)|*.gif;*.jpg;*.jpeg;*.png;*.psd|
}
saveFileDialog.Filter = filter;
DialogResult dResult = saveFileDialog.ShowDialog();
if (dResult == DialogResult.OK)
{
string defaultExt = ".docx";
//string filter = string.Empty;
//string saveFileDialogTitle = "保存文件";
saveFileDialog.SupportMultiDottedExtensions = true;
saveFileDialog.AutoUpgradeEnabled = true;
saveFileDialog.AddExtension = true;
saveFileDialog.CheckPathExists = true;
saveFileDialog.CheckFileExists = true;
saveFileDialog.DefaultExt = defaultExt;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.OverwritePrompt = true;
saveFileDialog.Title = saveFileDialogTitle;
saveFileDialog.ValidateNames = true;
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
//添加后界面没变化 Win7 + VS11
saveFileDialog.ShowHelp = true;
filePathName = saveFileDialog.FileName;
if (true == isReadOnly)
{
saveFileDialog.OpenFile(); //打开只读文件,即开启一使用该文件进程,防止其他进程操作该文件
}
saveFileDialog.Dispose();
}
return filePathName;
}
}
}

测试调用代码如下:
RarForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CompressProj
{
public partial class RarForm : Form
{
private FileOperate fileOperate = FileOperate.getInstance();
private RarOperate rarOperate = RarOperate.getInstance();
private ZipOperate zipOperate = ZipOperate.getInstance();
public RarForm()
{
InitializeComponent();
}
private void btnCompress_Click(object sender, EventArgs e)
{
string filter = "TXT(*.txt)|*.txt|Word(*.doc,*.docx)|*.doc;*.docx|AllFiles(*.*)|*.*";
string openFileDialogTitle = "压缩文件";
string compressFilePathName = fileOperate.OpenFile(this.openFileDialog1, filter, openFileDialogTitle,true);
if (string.IsNullOrEmpty(compressFilePathName) || string.IsNullOrWhiteSpace(compressFilePathName))
{
return;
}
this.openFileDialog1.HelpRequest += new EventHandler(openFileDialog1_HelpRequest);
string objectRarPathName = compressFilePathName.Substring(0,compressFilePathName.LastIndexOf('.')) + ".rar";
string rarPathName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Rar.exe";
string password = string.Empty;//"shenc";
CompressResults compressResult = rarOperate.CompressObject(rarPathName, compressFilePathName, objectRarPathName, password);
if (CompressResults.Success == compressResult)
{
MessageBox.Show(objectRarPathName);
}
}
private void openFileDialog1_HelpRequest(object sender, EventArgs e)
{
MessageBox.Show("HelpRequest!");
}
private void btnUncompress_Click(object sender, EventArgs e)
{
string filter = "Rar(*.rar)|*.rar";
string openFileDialogTitle = "解压文件";
string unCompressFilePathName = fileOperate.OpenFile(this.openFileDialog1, filter, openFileDialogTitle, false);
if (string.IsNullOrEmpty(unCompressFilePathName) || string.IsNullOrWhiteSpace(unCompressFilePathName))
{
return;
}
string objectPath = unCompressFilePathName.Substring(0, unCompressFilePathName.LastIndexOf('.'));
string rarPathName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Rar.exe";
string password = string.Empty;//"shenc";
UnCompressResults unCompressResult = rarOperate.unCompressRAR(rarPathName, unCompressFilePathName, objectPath, password);
if (UnCompressResults.Success == unCompressResult)
{
MessageBox.Show(objectPath);
}
}
private void btnCompressZip_Click(object sender, EventArgs e)
{
string filter = "TXT(*.txt)|*.txt|Word(*.doc,*.docx)|*.doc;*.docx|AllFiles(*.*)|*.*";
string openFileDialogTitle = "压缩文件";
string compressFilePathName = fileOperate.OpenFile(this.openFileDialog1, filter, openFileDialogTitle, false);
if (string.IsNullOrEmpty(compressFilePathName) || string.IsNullOrWhiteSpace(compressFilePathName))
{
return;
}
//this.openFileDialog1.HelpRequest += new EventHandler(openFileDialog1_HelpRequest);
string password = string.Empty;//"shenc";
string objectZipPathName = compressFilePathName.Substring(0, compressFilePathName.LastIndexOf('.')) + ".zip";
CompressResults compressResult = zipOperate.Compress7zZip(compressFilePathName, objectZipPathName, password); //压缩文件
////测试压缩文件夹:压缩文件不能放在被压缩文件内,否则报“文件夹被另一进程使用中”错误。
//string objectPath = compressFilePathName.Substring(0, compressFilePathName.LastIndexOf('\\'));
//objectZipPathName = objectPath + ".zip";
//CompressResults compressResult = zipOperate.Compress7zZip(objectPath, objectZipPathName, password); //压缩文件夹
if (CompressResults.Success == compressResult)
{
MessageBox.Show(objectZipPathName);
}
}
private void btnUnCompressZip_Click(object sender, EventArgs e)
{
string filter = "Zip(*.zip)|*.zip";
string openFileDialogTitle = "解压文件";
string unCompressFilePathName = fileOperate.OpenFile(this.openFileDialog1, filter, openFileDialogTitle, false);
if (string.IsNullOrEmpty(unCompressFilePathName) || string.IsNullOrWhiteSpace(unCompressFilePathName))
{
return;
}
string objectPath = unCompressFilePathName.Substring(0, unCompressFilePathName.LastIndexOf('.'));
string password = string.Empty;//"shenc";
UnCompressResults unCompressResult = zipOperate.UnCompress7zZip(unCompressFilePathName, objectPath, password);
if (UnCompressResults.Success == unCompressResult)
{
MessageBox.Show(objectPath);
}
}
}
}

C#压缩、解压缩文件(夹)(rar、zip)的更多相关文章
- 使用VC++压缩解压缩文件夹
前言 项目中要用到一个压缩解压缩的模块, 看了很多文章和源代码, 都不是很称心, 现在把我自己实现的代码和大家分享. 要求: 1.使用Unicode(支持中文). 2.使用源代码.(不使用静态或 ...
- Linux的压缩/解压缩文件处理 zip & unzip
Linux的压缩/解压缩命令详解及实例 压缩服务器上当前目录的内容为xxx.zip文件 zip -r xxx.zip ./* 解压zip文件到当前目录 unzip filename.zip 另:有些服 ...
- C#压缩文件夹至zip,不包含所选文件夹【转+修改】
转自园友:jimcsharp的博文C#实现Zip压缩解压实例[转] 在此基础上,对其中的压缩文件夹方法略作修正,并增加是否对父文件夹进行压缩的方法.(因为笔者有只压缩文件夹下的所有文件,却不想将选中的 ...
- Python压缩指定文件及文件夹为zip
Python压缩指定的文件及文件夹为.zip 代码: def zipDir(dirpath,outFullName): """ 压缩指定文件夹 :param dirpat ...
- linux 压缩当前文件夹下所有文件
linux zip压缩.压缩当前文件夹下所有文件,压缩为a.zip.命令行的方法是怎样. zip -r fileName.zip 文件夹名 tar tar命令可以用来压缩打包单文件.多个文件.单个 ...
- python实现压缩当前文件夹下的所有文件
import os import zipfile def zipDir(dirpath, outFullName): ''' 压缩指定文件夹 :param dirpath: 目标文件夹路径 :para ...
- albert1017 Linux下压缩某个文件夹(文件夹打包)
albert1017 Linux下压缩某个文件夹(文件夹打包) tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录例子:把 ...
- php读取excel,以及php打包文件夹为zip文件
1.把文件下载到本地,放在在Apache环境下2.d.xlsx是某游戏的服务器名和玩家列表,本程序只适合此种xlsx文件结构,其他结构请修改index.php源码3.访问zip.php的功能是把生成的 ...
- shell 批量压缩指定文件夹及子文件夹内图片
shell 批量压缩指定文件夹及子文件夹内图片 用户上传的图片,一般都没有经过压缩,造成空间浪费.因此须要编写一个程序,查找文件夹及子文件夹的图片文件(jpg,gif,png),将大于某值的图片进行压 ...
- gulp插件实现压缩一个文件夹下不同目录下的js文件(支持es6)
gulp-uglify:压缩js大小,只支持es5 安装: cnpm: cnpm i gulp-uglify -D yarn: yarn add gulp-uglify -D 使用: 代码实现1:压缩 ...
随机推荐
- Android开发了解——AIDL
AIDL:Android Interface Definition Language,即Android接口定义语言. 什么是AIDL Android系统中的进程之间不能共享内存,因此,需要提供一些机制 ...
- HTML5拖拽功能drag
1.创建拖拽对象 给需要拖拽的元素设置draggable属性,它有三个值: true:元素可以被拖拽:false:元素不能被拖拽:auto: 浏览器自己判断元素是否能被拖拽. 2.处理拖拽事件当我们拖 ...
- [转]在SQLServer中实现Sequence的高效方法
如果在ORACLE里面用惯了Sequence的兄弟们,要在SqlServer里实现Sequence,就会发现没有现成的Sequence对象可以Create了.那应该怎么办呢? 当然这点小问题是难不倒我 ...
- ios code style
注释 建议使用VVDocumenter插件 多行注释 格式: /** 注释内容 */ 单行注释 格式: ///在对文件.类.函数进行注释时推荐使用多行注释,在函数体内对代码块进行注释时,使用单行注释 ...
- IOS 高级开发 KVC(一)
熟练使用KVC 可以再开发过程中可以给我们带来巨大的好处,尤其是在json 转模型的时候,KVC让程序员摆脱了繁琐无营养的代码堆积.减少代码量就是减少出错的概率.KVC 用起来很灵活,这种灵活的基础是 ...
- String练习
/*1,模拟一个trim方法,去除字符串两端的空格. 思路: 1,判断字符串第一个位置是否是空格,如果是继续向下判断,直到不是空格为止. 结尾处判断空格也是如此. 2, ...
- IO流03_流的分类和概述
[概述] Java的IO流是实现输入/输出的基础,它可以方便的实现数据的输入/输出操作. Java中把不同的输入/输出源(键盘.文件.网络连接)抽象表述为"流"(Stream). ...
- 第一个 MIC shared_memory 程序
设置Intel编译器的运行环境 在terminal中执行编译器的环境脚本 compilervars.sh: source <install-dir>/bin/compilervars.sh ...
- HeadFirst设计模式-前言总结
1 鸭子抽象类 class Duck { quack(); swim(); virtual display()=0 }; 现在如果让鸭子能够飞 class Duck { quack(); swim() ...
- 第32条:用EnumSet代替位域
如果一个枚举类型的元素主要用在集合中,一般使用int枚举模式,将2的不同倍数赋予每个常量: public class Text { public static final int STYLE_BOLD ...