`
hzy3774
  • 浏览: 985412 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

C#调用WinRar来解压文件

 
阅读更多
class UseWinRar
    {
        private string rarExeFile = null;//WinRar.exe路径
        private bool useAble = false;//标志WinRar是否可用

        public UseWinRar()//构造方法
        {
            rarExeFile = getRarExe();
            useAble = !string.IsNullOrEmpty(rarExeFile);//如果WinRar.exe路径不为空,说明可用
        }

        public static string getRarExe()//获取WinRar所在磁盘路径
        {
            string rarExe = null;
            RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe");
            if (regKey == null)
            {
                return null;
            }
            rarExe = regKey.GetValue("").ToString();
            regKey.Close();//关闭注册表
            return rarExe;
        }

        public bool exeRarCmd(string cmd)//执行某个命令
        {
            if (!useAble)
            {
                return false;
            }
            Process process = new Process();//新建一个过程
            ProcessStartInfo startInfo = new ProcessStartInfo(rarExeFile);//新建一个启动信息
            startInfo.Arguments = cmd;//设置启动信息的执行参数
            //startInfo.WorkingDirectory = workDirectory;//设置启动信息的工作目录
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;//设置程序后台运行
            process.StartInfo = startInfo;//设置过程的启动信息
            process.Start();//开始过程
            return true;
        }

        public bool unZipAll(string zipFile, string targetDirectory)//将指定压缩文件解压到指定目录
        {
            if (! File.Exists(zipFile))
            {
                return false;
            }
            string zipCmd = "x " + zipFile +" "+ targetDirectory + " -y -ibck";//后台解压压缩文件中全部文件到指定目录
            exeRarCmd(zipCmd);//执行解压操作
            return true;
        }

        public bool unZipToCurrentDirectory(string zipFile)//将压缩文件解压到当前目录
        {
            if (!File.Exists(zipFile))
            {
                return false;
            }
            FileInfo fileInfo = new FileInfo(zipFile);
            return unZipAll(zipFile, fileInfo.DirectoryName);
        }
    }

 Main:

public static void Main()
        {
            UseWinRar rar = new UseWinRar();
            string[] zipFiles = Directory.GetFiles(Environment.CurrentDirectory, "*.zip");//获取所有zip文件路径
            foreach (string zipFile in zipFiles)
            {
                rar.unZipToCurrentDirectory(zipFile);
            }
        }

 这样便可以实现后台解压当前目录下所有*.zip文件。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics