Ejemplo n.º 1
0
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="path"></param>
        /// <param name="zipPath"></param>
        /// <returns></returns>
        public static bool Zip(string path, string zipPath)
        {
            bool isPathIsFile = false;

            if (File.Exists(path))
            {
                isPathIsFile = true;
            }
            else if (Directory.Exists(path))
            {
                isPathIsFile = false;
            }
            else
            {
                throw new Exception($"未知的文件:{path}");
            }

            string[] files = null;
            if (isPathIsFile)
            {
                files = new string[] { path }
            }
            ;
            else
            {
                files = Directory.GetFiles(path, "*", SearchOption.AllDirectories);
            }

            if (files is null)
            {
                throw new ArgumentNullException(nameof(files));
            }

            object objLock = new object();

            using (Stream stream = new FileStream(zipPath, FileMode.Create, FileAccess.Write))
            {
                ZipOutputStream output = new ZipOutputStream(stream);

                List <Task> tasks = new List <Task>();

                foreach (string _file in files)
                {
                    var task = new Task((o) => {
                        string file = o as string;
                        string name = string.Empty;
                        if (isPathIsFile)
                        {
                            name = TxFile.GetFileName(file);
                        }
                        else
                        {
                            name = file.Replace(path + "\\", "").Replace("\\", "/");
                        }

                        byte[] data    = null;
                        ZipEntry entry = new ZipEntry(name);
                        var info       = new FileInfo(file);
                        entry.DateTime = info.LastWriteTime;
                        data           = File.ReadAllBytes(file);

                        lock (objLock)
                        {
                            output.PutNextEntry(entry);
                            if (data != null)
                            {
                                output.Write(data, 0, data.Length);
                            }
                        }
                    }, _file);
                    task.Start();
                    tasks.Add(task);
                }

                Task.WaitAll(tasks.ToArray());
                output.Finish();
                output.Close();
            }

            return(true);
        }