zoukankan      html  css  js  c++  java
  • C# 文件操作

    public class FileOperation
        {
            #region 压缩文件
            /// <summary>    
            /// 压缩文件    
            /// </summary>    
            /// <param name="fileNames">要打包的文件列表</param>    
            /// <param name="GzipFileName">目标文件名</param>    
            /// <param name="CompressionLevel">压缩品质级别(0~9)</param>    
            /// <param name="deleteFile">是否删除原文件</param>  
            public static void CompressFile(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
            {
                ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
                try
                {
                    s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression    
                    foreach (FileInfo file in fileNames)
                    {
                        FileStream fs = null;
                        try
                        {
                            fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
                        }
                        catch
                        { continue; }
                        //  方法二,将文件分批读入缓冲区    
                        byte[] data = new byte[2048];
                        int size = 2048;
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
                        entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
                        s.PutNextEntry(entry);
                        while (true)
                        {
                            size = fs.Read(data, 0, size);
                            if (size <= 0) break;
                            s.Write(data, 0, size);
                        }
                        fs.Close();
                        if (deleteFile)
                        {
                            file.Delete();
                        }
                    }
                }
                finally
                {
                    s.Finish();
                    s.Close();
                }
            }
            /// <summary>    
            /// 压缩文件夹    
            /// </summary>    
            /// <param name="dirPath">要打包的文件夹</param>    
            /// <param name="GzipFileName">目标文件名</param>    
            /// <param name="CompressionLevel">压缩品质级别(0~9)</param>    
            /// <param name="deleteDir">是否删除原文件夹</param>  
            public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
            {
                //压缩文件为空时默认与压缩文件夹同一级目录    
                if (GzipFileName == string.Empty)
                {
                    GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
                    GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
                }
                //if (Path.GetExtension(GzipFileName) != ".zip")  
                //{  
                //    GzipFileName = GzipFileName + ".zip";  
                //}  
                using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
                {
                    zipoutputstream.SetLevel(CompressionLevel);
                    Crc32 crc = new Crc32();
                    Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
                    foreach (KeyValuePair<string, DateTime> item in fileList)
                    {
                        FileStream fs = File.OpenRead(item.Key.ToString());
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
                        entry.DateTime = item.Value;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        zipoutputstream.PutNextEntry(entry);
                        zipoutputstream.Write(buffer, 0, buffer.Length);
                    }
                }
                if (deleteDir)
                {
                    Directory.Delete(dirPath, true);
                }
            }
            #endregion
            #region 获取所有文件
            /// <summary>    
            /// 获取所有文件    
            /// </summary>    
            /// <returns></returns>    
            public static Dictionary<string, DateTime> GetAllFies(string dir)
            {
                Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
                DirectoryInfo fileDire = new DirectoryInfo(dir);
                if (!fileDire.Exists)
                {
                    throw new System.IO.FileNotFoundException("没有找到该目录:" + fileDire.FullName );
                }
                GetAllDirFiles(fileDire, FilesList);
                GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
                return FilesList;
            }
            #endregion
            #region  获取一个文件夹下的所有文件夹里的文件
            /// <summary>    
            /// 获取一个文件夹下的所有文件夹里的文件    
            /// </summary>    
            /// <param name="dirs"></param>    
            /// <param name="filesList"></param>    
            public static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
            {
                foreach (DirectoryInfo dir in dirs)
                {
                    foreach (FileInfo file in dir.GetFiles("*.*"))
                    {
                        filesList.Add(file.FullName, file.LastWriteTime);
                    }
                    GetAllDirsFiles(dir.GetDirectories(), filesList);
                }
            }
            #endregion
            /// <summary>    
            /// 获取一个文件夹下的文件    
            /// </summary>    
            /// <param name="dir">目录名称</param>    
            /// <param name="filesList">文件列表HastTable</param>    
            public static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    filesList.Add(file.FullName, file.LastWriteTime);
                }
            }
          
            #region 解压缩文件
            /// <summary>    
            /// 解压缩文件    
            /// </summary>    
            /// <param name="GzipFile">压缩包文件名</param>    
            /// <param name="targetPath">解压缩目标路径</param>           
            public static void Decompress(string GzipFile, string targetPath)
            {
                //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";    
                string directoryName = targetPath;
                if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录    
                string CurrentDirectory = directoryName;
                byte[] data = new byte[2048];
                int size = 2048;
                ZipEntry theEntry = null;
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
                {
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        if (theEntry.IsDirectory)
                        {// 该结点是目录    
                            if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                        }
                        else
                        {
                            if (theEntry.Name != String.Empty)
                            {
                                //  检查多级目录是否存在  
                                if (theEntry.Name.Contains("//"))
                                {
                                    string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);
                                    if (!Directory.Exists(parentDirPath))
                                    {
                                        Directory.CreateDirectory(CurrentDirectory + parentDirPath);
                                    }
                                }
    
                                //解压文件到指定的目录    
                                using (FileStream streamWriter = File.Create(CurrentDirectory + "\" + theEntry.Name))
                                {
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);
                                        if (size <= 0) break;
                                        streamWriter.Write(data, 0, size);
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                    }
                    s.Close();
                }
            }
            #endregion
    
            #region  压缩解压rar
            /// <summary>
            /// 解压RAR和ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe))
            /// </summary>
            /// <param name="UnPath">解压后文件保存目录</param>
            /// <param name="rarPathName">待解压文件存放绝对路径(包括文件名称)</param>
            /// <param name="IsCover">所解压的文件是否会覆盖已存在的文件(如果不覆盖,所解压出的文件和已存在的相同名称文件不会共同存在,只保留原已存在文件)</param>
            /// <param name="PassWord">解压密码(如果不需要密码则为空)</param>
            /// <returns>true(解压成功);false(解压失败)</returns>
            public static bool UnRarfile(string UnPath, string rarPathName, bool IsCover, string PassWord)
            {
                if (!Directory.Exists(UnPath))
                    Directory.CreateDirectory(UnPath);
                Process Process1 = new Process();
                Process1.StartInfo.FileName = "Winrar.exe";
                Process1.StartInfo.CreateNoWindow = true;
                string cmd = "";
                if (!string.IsNullOrEmpty(PassWord) && IsCover)
                    //解压加密文件且覆盖已存在文件( -p密码 )
                    cmd = string.Format(" x -p{0} -o+ {1} {2} -y", PassWord, rarPathName, UnPath);
                else if (!string.IsNullOrEmpty(PassWord) && !IsCover)
                    //解压加密文件且不覆盖已存在文件( -p密码 )
                    cmd = string.Format(" x -p{0} -o- {1} {2} -y", PassWord, rarPathName, UnPath);
                else if (IsCover)
                    //覆盖命令( x -o+ 代表覆盖已存在的文件)
                    cmd = string.Format(" x -o+ {0} {1} -y", rarPathName, UnPath);
                else
                    //不覆盖命令( x -o- 代表不覆盖已存在的文件)
                    cmd = string.Format(" x -o- {0} {1} -y", rarPathName, UnPath);
                //命令
                Process1.StartInfo.Arguments = cmd;
                Process1.Start();
                Process1.WaitForExit();//无限期等待进程 winrar.exe 退出
                //Process1.ExitCode==0指正常执行,Process1.ExitCode==1则指不正常执行
                if (Process1.ExitCode == 0)
                {
                    Process1.Close();
                    return true;
                }
                else
                {
                    Process1.Close();
                    return false;
                }
    
            }
    
            /// <summary>
            /// 压缩文件成RAR或ZIP文件(需存在Winrar.exe(只要自己电脑上可以解压或压缩文件就存在Winrar.exe))
            /// </summary>
            /// <param name="filesPath">将要压缩的文件夹或文件的绝对路径</param>
            /// <param name="rarPathName">压缩后的压缩文件保存绝对路径(包括文件名称)</param>
            /// <param name="IsCover">所压缩文件是否会覆盖已有的压缩文件(如果不覆盖,所压缩文件和已存在的相同名称的压缩文件不会共同存在,只保留原已存在压缩文件)</param>
            /// <param name="PassWord">压缩密码(如果不需要密码则为空)</param>
            /// <returns>true(压缩成功);false(压缩失败)</returns>
            public static bool CondenseRarOrZip(string filesPath, string rarPathName, bool IsCover, string PassWord)
            {
                string rarPath = Path.GetDirectoryName(rarPathName);
                if (!Directory.Exists(rarPath))
                    Directory.CreateDirectory(rarPath);
                Process Process1 = new Process();
                Process1.StartInfo.FileName = "Winrar.exe";
                Process1.StartInfo.CreateNoWindow = true;
                string cmd = "";
                if (!string.IsNullOrEmpty(PassWord) && IsCover)
                    //压缩加密文件且覆盖已存在压缩文件( -p密码 -o+覆盖 )
                    cmd = string.Format(" a -ep1 -p{0} -o+ {1} {2} -r", PassWord, rarPathName, filesPath);
                else if (!string.IsNullOrEmpty(PassWord) && !IsCover)
                    //压缩加密文件且不覆盖已存在压缩文件( -p密码 -o-不覆盖 )
                    cmd = string.Format(" a -ep1 -p{0} -o- {1} {2} -r", PassWord, rarPathName, filesPath);
                else if (string.IsNullOrEmpty(PassWord) && IsCover)
                    //压缩且覆盖已存在压缩文件( -o+覆盖 )
                    cmd = string.Format(" a -ep1 -o+ {0} {1} -r", rarPathName, filesPath);
                else
                    //压缩且不覆盖已存在压缩文件( -o-不覆盖 )
                    cmd = string.Format(" a -ep1 -o- {0} {1} -r", rarPathName, filesPath);
                //命令
                Process1.StartInfo.Arguments = cmd;
                Process1.Start();
                Process1.WaitForExit();//无限期等待进程 winrar.exe 退出
                //Process1.ExitCode==0指正常执行,Process1.ExitCode==1则指不正常执行
                if (Process1.ExitCode == 0)
                {
                    Process1.Close();
                    return true;
                }
                else
                {
                    Process1.Close();
                    return false;
                }
    
            }
            #endregion
            // <summary>
            /// 删除所有文件(文件夹)包括本身
            /// </summary>
            /// <param name="dir"></param>
            public void DeleteFolderAll(string dir)
            {
                if (Directory.Exists(dir)) //如果存在这个文件夹删除之   
                {
                    foreach (string d in Directory.GetFileSystemEntries(dir))
                    {
                        if (File.Exists(d))
                            File.Delete(d); //直接删除其中的文件                          
                        else
                            DeleteFolderAll(d); //递归删除子文件夹   
                    }
                    Directory.Delete(dir, true); //删除已空文件夹                   
                }
            }
    
            /// <summary>
            /// 删除某个路径下的所有东西
            /// </summary>
            /// <param name="dirPath"></param>
            public static void DeleteFolder(string dirPath)
            {
                if (Directory.Exists(dirPath))
                {
                    foreach (string content in Directory.GetFileSystemEntries(dirPath))
                    {
                        if (Directory.Exists(content))
                        {
                            Directory.Delete(content, true);
                        }
                        else if (File.Exists(content))
                        {
                            File.Delete(content);
                        }
                    }
                }
            }
  • 相关阅读:
    IOptions、IOptionsMonitor、IOptionsSnapshot的区别
    基于 .NET 的 FluentValidation 验证教程
    挂载NFS网络文件系统教程
    gcc简要知识点
    二叉树遍历(前序、中序、后序、层次、广度优先、深度优先遍历)
    项目管理的一些知识总结
    Vue从零开发单页应用程序项目
    CRC校验原理
    Linux 文件搜索神器 find 实战详解
    Linux 三剑客之 grep、sed、awk 使用详解
  • 原文地址:https://www.cnblogs.com/wxxf/p/12895151.html
Copyright © 2011-2022 走看看