代碼如下:
以下為引用的內容:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Com.ImYan.CabHelper
{
/// <summary>
/// CAB文件壓縮解壓類
/// </summary>
public class Cab
{
#region 屬性列表 PropertIEs
private string _cabFileName;
/// <summary>
/// 生成或者解壓的Cab文件路徑
/// </summary>
public string CabFileName
{
get { return _cabFileName; }
set { _cabFileName = value; }
}
private List<string> _fileList=new List<string>();
/// <summary>
/// “將被壓縮”或者“解壓出”的文件列表
/// </summary>
public List<string> FileList
{
get { return _fileList; }
set { _fileList = value; }
}
/// <summary>
/// 臨時目錄
/// </summary>
private string TempDir;
#endregion
#region 構造函數 Structure
public Cab()
{
//指定並創建臨時目錄
this.TempDir = Environment.GetFolderPath(Environment.SpecialFolder.Templates);
this.TempDir = string.Format("{0}\\CabTemp\\", this.TempDir);
//如果存在,先刪除
if (Directory.Exists(this.TempDir)) Directory.Delete(this.TempDir,true);
Directory.CreateDirectory(this.TempDir);
}
#endregion
#region 私有方法列表 Private Methods
/// <summary>
/// 生成 list.txt 文件
/// </summary>
private string CreateListFile()
{
try
{
string listFilePath = Path.Combine(this.TempDir, "list.txt");
string listContent = string.Empty;//文件內容
for (int i = 0; i < this.FileList.Count; i++)
{
listContent += string.Format("\"{0}\"\r\n", this.FileList[i]);
}
using (FileStream fs = new FileStream(listFilePath, FileMode.Create, FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
sw.Write(listContent);
sw.Flush();
sw.Close();
fs.Close();
}
return listFilePath;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 執行CMD命令
/// </summary>
private string RunCommand(string cmdString)
{
Process p = new Process();
//啟動DOS程序
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;//不用Shell啟動
p.StartInfo.RedirectStandardInput = true;//重定向輸入
p.StartInfo.RedirectStandardOutput = true;//重定向輸出
p.StartInfo.CreateNoWindow = true;//不顯示窗口
p.Start();//開始進程
p.StandardInput.WriteLine(cmdString);// 向cmd.exe輸入command
p.StandardInput.WriteLine("exit");//結束
p.WaitForExit(60000);//等等執行完成
string outPutString = p.StandardOutput.ReadToEnd();// 得到cmd.exe的輸出
p.Close();
return outPutString;
}
/// <summary>
/// 分析並找到cab文件,然後提取到輸出目錄
/// </summary>
private void MoveCabFile()
{
string cabFilePath = string.Empty;
List<string> allFilesInTempDir = this.GetFilesFromDir(this.TempDir);
foreach (string file in allFilesInTempDir)
{
if (Path.GetExtension(file).ToLower() == ".cab")
{
cabFilePath = file;
break;
}
else
{
//否則刪除之
File.Delete(file);
}
}
//轉移文件
File.Move(cabFilePath, this.CabFileName);
}
/// <summary>
/// 從指定目錄讀取文件列表
/// </summary>
/// <param name="dir">要搜索的目錄</param>
/// <param name="filters">後綴列表</param>
/// <returns></returns>
private List<string> GetFilesFromDir(string dir)
{
List<string> files = new List<string>(Directory.GetFiles(dir));
List<string> dirs = new List<string>(Directory.GetDirectorIEs(dir));
foreach (string childDir in dirs)
{
files.AddRange(this.GetFilesFromDir(childDir));
}
return files;
}
/// <summary>
/// 從DOS命令返回的結果,分析並得到解壓後的文件列表
/// </summary>
/// <param name="cmdResult">DOS返回的結果</param>
private void GetExpandedFileByCmdResult(string cmdResult)
{
//文件列表
this._fileList = new List<string>();
//分割結果
string[] resultRowList = cmdResult.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntrIEs);
//關鍵字
string keyString = string.Format("將 {0} 展開成",this.CabFileName.ToLower());
foreach (string resultRow in resultRowList)
{
if (resultRow.Trim().StartsWith(keyString))
{
string filePath = resultRow.Replace(keyString, "").Trim().Replace("。", "");
if (File.Exists(filePath))
{
this._fileList.Add(filePath);
}
}
}
}
#endregion
#region 公有方法列表 Public Methods
/// <summary>
/// 制作CAB文件
/// 【執行此方法前請先指定“FileList”屬性的值】
/// </summary>
/// <param name="errorInfo">返回的錯誤信息</param>
/// <returns>是否成功</returns>
public bool MakeCab(out string errorInfo)
{
errorInfo = string.Empty;
try
{
//第一步:寫臨時文件 list.txt
string listFile = this.CreateListFile();
if (File.Exists(listFile) == false) throw new Exception("生成文件 list.txt 失敗!");
//第二步:執行CMD命令
string cmdString = "makecab /F list.txt";
string cmdResult = this.RunCommand(cmdString);
//第三步:分析並找到cab文件,然後提取到輸出目錄
this.MoveCabFile();
if (File.Exists(this.CabFileName))
{
return true;
}
else
{
errorInfo = string.Format("文件 {0} 生成失敗!", this.CabFileName);
return false;
}
}
catch (Exception ex)
{
errorInfo = ex.Message;
return false;
}
}
/// <summary>
/// 解壓縮CAB文件
/// 【執行此方法前請先指定“CabFileName”屬性的值】
/// </summary>
/// <param name="errorInfo">返回的錯誤信息</param>
/// <returns>是否成功</returns>
public bool ExpandCab(out string errorInfo)
{
errorInfo = string.Empty;
try
{
//第一步:檢查源文件和目錄文件夾
if (File.Exists(this.CabFileName) == false) throw new Exception("CAB源文件不存在!請指定正確的CabFileName的值!");
if (Directory.Exists(this.TempDir) == false) Directory.CreateDirectory(this.TempDir);
//第二步:執行CMD命令
string tempPath = this.TempDir.EndsWith("\\") ? this.TempDir.Substring(0, this.TempDir.Length - 1) : this.TempDir;
string cmdString = string.Format("expand \"{0}\" \"{1}\" -f:*", this.CabFileName, tempPath);
string cmdResult = this.RunCommand(cmdString);
//第三步:分析得到解壓的文件列表
this.GetExpandedFileByCmdResult(cmdResult);
return true;
}
catch (Exception ex)
{
errorInfo = ex.Message;
return false;
}
}
#endregion
}
}