文件夾和文件壓縮

///<summary>

        ///功能:壓縮文件(暫時只壓縮文件夾下一級目錄中的文件,文件夾及其子級被忽略)

        ///</summary>

        ///<paramname="dirPath">被壓縮的文件夾夾路徑</param>

        ///<paramname="zipFilePath">生成壓縮文件的路徑,爲空則默認與被壓縮文件夾同一級目錄,名稱爲:文件夾名+.zip</param>

        ///<paramname="err">出錯信息</param>

        ///<returns>是否壓縮成功</returns>

        publicboolZipFile(string dirPath,stringzipFilePath,outstringerr)

        {

           err = "";

            if(dirPath == string.Empty)

            {

               err = "要壓縮的文件夾不能爲空!";

               return false;

            }

            if(!Directory.Exists(dirPath))

            {

               err = "要壓縮的文件夾不存在!";

               return false;

            }

            //壓縮文件名爲空時使用文件夾名+.zip

            if(zipFilePath == string.Empty)

            {

               if (dirPath.EndsWith("\\"))

               {

                   dirPath = dirPath.Substring(0, dirPath.Length - 1);

               }

               zipFilePath = dirPath + ".zip";

            }

 

            try

            {

               string[] filenames =Directory.GetFiles(dirPath);

               using (ZipOutputStreams =newZipOutputStream(File.Create(zipFilePath)))

               {

                   s.SetLevel(9);

                   byte[] buffer =newbyte[4096];

                   foreach (stringfilein filenames)

                   {

                        ZipEntry entry =newZipEntry(Path.GetFileName(file));

                        entry.DateTime = DateTime.Now;

                        s.PutNextEntry(entry);

                        using(FileStream fs =File.OpenRead(file))

                        {

                            intsourceBytes;

                            do

                            {

                                sourceBytes =fs.Read(buffer, 0, buffer.Length);

                                s.Write(buffer,0, sourceBytes);

                            } while(sourceBytes > 0);

                        }

                   }

                   s.Finish();

                   s.Close();

               }

            }

            catch(Exception ex)

            {

               err = ex.Message;

               return false;

            }

            returntrue;

        }
發佈了38 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章