Example #1
0
 public static void UnZipFiles(string zipPathAndFile, string outputFolder)
 {
     var s = new ZipInputStream(File.OpenRead(zipPathAndFile));
     ZipEntry theEntry;
     var tmpEntry = String.Empty;
     while ((theEntry = s.GetNextEntry()) != null)
     {
         var directoryName = outputFolder;
         var fileName = Path.GetFileName(theEntry.Name);
         if (directoryName != "")
             Directory.CreateDirectory(directoryName);
         if (fileName != String.Empty)
             if (theEntry.Name.IndexOf(".ini") < 0)
             {
                 var fullPath = directoryName + "\\" + theEntry.Name;
                 fullPath = fullPath.Replace("\\ ", "\\");
                 string fullDirPath = Path.GetDirectoryName(fullPath);
                 if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                 FileStream streamWriter = File.Create(fullPath);
                 int size = 2048;
                 byte[] data = new byte[2048];
                 while (true)
                 {
                     size = s.Read(data, 0, data.Length);
                     if (size > 0)
                         streamWriter.Write(data, 0, size);
                     else
                         break;
                 }
                 streamWriter.Close();
             }
     }
     s.Close();
     File.Delete(zipPathAndFile);
 }
  public static void unzipFolder( string zipFilename, string folderPath, string dstFolder )
  {
    byte[] data = new byte[4096];

    using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename)))
    {
      ZipEntry entry;
      while ((entry = inputStream.GetNextEntry()) != null)
      {
        if ( entry.FileName.StartsWith( folderPath ) && !entry.IsDirectory )
        {
          char[] charsToTrim = { '/' };
          string entryName = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim );
          string entryFilename = entryName;
          string entryFolder = dstFolder;

          int idx = entryFilename.LastIndexOf( "/" );
          if ( idx >= 0 )
          {
            entryFolder = dstFolder + "/" + entryFilename.Substring( 0, idx );
            entryFilename = entryFilename.Substring( idx+1 );
          }

          DirectoryInfo dirInfo = new DirectoryInfo(entryFolder);
          if ( !dirInfo.Exists )
          {
            Directory.CreateDirectory( entryFolder );
          }

          Message.Log( "Copying file to '" + entryFolder + "/" + entryFilename + "'" );
          FileStream outputStream = new FileStream( entryFolder + "/" + entryFilename, FileMode.Create, FileAccess.Write );

          int size = inputStream.Read( data, 0, data.Length );
          while ( size > 0 )
          {
            outputStream.Write( data, 0, size );
            size = inputStream.Read( data, 0, data.Length );
          }

          outputStream.Close();
        }
      }
    }
  }
Example #3
0
        public void EmptyZipEntries()
        {
            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            for (var i = 0; i < 10; ++i)
            {
                outStream.PutNextEntry(new ZipEntry(i.ToString()));
            }
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);

            var extractCount = 0;
            ZipEntry entry;
            var decompressedData = new byte[100];

            while ((entry = inStream.GetNextEntry()) != null)
            {
                while (true)
                {
                    var numRead = inStream.Read(decompressedData, extractCount, decompressedData.Length);
                    if (numRead <= 0)
                    {
                        break;
                    }
                    extractCount += numRead;
                }
            }
            inStream.Close();
            Assert.AreEqual(extractCount, 0, "No data should be read from empty entries");
        }
Example #4
0
        private void ExerciseZip(CompressionMethod method, int compressionLevel,
                                 int size, string password, bool canSeek)
        {
            byte[] originalData = null;
            var compressedData = MakeInMemoryZip(ref originalData, method, compressionLevel, size, password, canSeek);

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            using (var inStream = new ZipInputStream(ms))
            {
                var decompressedData = new byte[size];
                if (password != null)
                {
                    inStream.Password = password;
                }

                var entry2 = inStream.GetNextEntry();

                if ((entry2.Flags & 8) == 0)
                {
                    Assert.AreEqual(size, entry2.Size, "Entry size invalid");
                }

                var currentIndex = 0;

                if (size > 0)
                {
                    var count = decompressedData.Length;

                    while (true)
                    {
                        var numRead = inStream.Read(decompressedData, currentIndex, count);
                        if (numRead <= 0)
                        {
                            break;
                        }
                        currentIndex += numRead;
                        count -= numRead;
                    }
                }

                Assert.AreEqual(currentIndex, size, "Original and decompressed data different sizes");

                if (originalData != null)
                {
                    for (var i = 0; i < originalData.Length; ++i)
                    {
                        Assert.AreEqual(decompressedData[i], originalData[i],
                                        "Decompressed data doesnt match original, compression level: " +
                                        compressionLevel);
                    }
                }
            }
        }
Example #5
0
        public void InvalidPasswordSeekable()
        {
            byte[] originalData = null;
            var compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated, 3, 500, "Hola", true);

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            var buf2 = new byte[originalData.Length];
            var pos = 0;

            var inStream = new ZipInputStream(ms);
            inStream.Password = "******";

            var entry2 = inStream.GetNextEntry();

            while (true)
            {
                var numRead = inStream.Read(buf2, pos, buf2.Length);
                if (numRead <= 0)
                {
                    break;
                }
                pos += numRead;
            }
        }
Example #6
0
        // Method invoked to install a downloaded update
        private void InstallUpdate(object sender, EventArgs e)
        {
            VersionChecker.VersionState updateInfo = stripNewVersion.Tag as VersionChecker.VersionState;

            if (updateInfo != null)
            {
                string   downloadOSFilename = new Uri(updateInfo.Url).PathAndQuery.Replace('/', Path.DirectorySeparatorChar);
                FileInfo downloadFileInfo   = new FileInfo(downloadOSFilename);

                FileInfo downloadedFile = new FileInfo($"{Core.UserDownloadsPath}{downloadFileInfo.Name}");
                string   extractionPath = downloadedFile.FullName.Substring(0, downloadedFile.FullName.IndexOf(downloadedFile.Extension));

                try
                {
                    if (downloadedFile.Exists)
                    {
                        using (ZipInputStream s = new ZipInputStream(File.OpenRead(downloadedFile.FullName)))
                        {
                            ZipEntry theEntry;
                            while ((theEntry = s.GetNextEntry()) != null)
                            {
                                string directoryName = extractionPath;
                                string fileName      = Path.GetFileName(theEntry.Name);

                                // create directory
                                if (directoryName.Length > 0)
                                {
                                    if (!Directory.Exists(directoryName))
                                    {
                                        Directory.CreateDirectory(directoryName);
                                    }
                                }

                                if (fileName != String.Empty)
                                {
                                    using (FileStream streamWriter = File.Create(string.Format("{0}\\{1}", directoryName, theEntry.Name)))
                                    {
                                        int    size = 2048;
                                        byte[] data = new byte[2048];
                                        while (true)
                                        {
                                            size = s.Read(data, 0, data.Length);
                                            if (size > 0)
                                            {
                                                streamWriter.Write(data, 0, size);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (File.Exists(extractionPath + "\\setup.exe"))
                        {
                            ProcessHelper.LaunchProcess($"{extractionPath}\\setup.exe");
                            ExitApplication();
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Example #7
0
 /// <summary>
 /// 解压缩文件
 /// </summary>
 /// <param name="ZipFileName">压缩文件</param>
 /// <param name="TargetFolder">目标文件夹</param>
 public static void UnZipFile(string ZipFileName, string TargetFolder)
 {
     if (ZipFileName.ToLower().Contains("rar"))
     {
         if (!Directory.Exists(TargetFolder))
         {
             Directory.CreateDirectory(TargetFolder);
         }
         using (Stream stream = File.OpenRead(ZipFileName))
         {
             var reader = ReaderFactory.Open(stream);
             while (reader.MoveToNextEntry())
             {
                 if (!reader.Entry.IsDirectory)
                 {
                     reader.WriteEntryToDirectory(TargetFolder);
                 }
             }
         }
     }
     else
     {
         if (!File.Exists(ZipFileName))
         {
             return;
         }
         FileStream     FileS       = File.OpenRead(ZipFileName);
         ZipInputStream zipInStream = new ZipInputStream(FileS);
         zipInStream.Password = Zipkey;
         //zipInStream.Password = "******";
         string FolderPath = Path.GetDirectoryName(TargetFolder);
         if (!Directory.Exists(TargetFolder))
         {
             Directory.CreateDirectory(FolderPath);
         }
         ZipEntry tEntry;
         while ((tEntry = zipInStream.GetNextEntry()) != null)
         {
             string fileName = Path.GetFileName(tEntry.Name);
             string tempPath = TargetFolder + "\\" + Path.GetDirectoryName(tEntry.Name);
             if (!Directory.Exists(tempPath))
             {
                 Directory.CreateDirectory(tempPath);
             }
             if (fileName != null && fileName.Length > 0)
             {
                 FileStream   streamWriter = File.Create(TargetFolder + "\\" + tEntry.Name);
                 byte[]       data         = new byte[2048];
                 System.Int32 size;
                 try
                 {
                     do
                     {
                         size = zipInStream.Read(data, 0, data.Length);
                         streamWriter.Write(data, 0, size);
                     } while (size > 0);
                 }
                 catch (System.Exception ex)
                 {
                     throw ex;
                 }
                 streamWriter.Close();
             }
         }
         zipInStream.Close();
     }
 }
        private void DownloadZFBAccount(DateTime beginDate, DateTime endDate, string bill_type)
        {
            IAopClient client = GetAopClient();
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            string root = Environment.CurrentDirectory.Replace("\\bin\\Debug", "") + "\\Download";

            //校验Download文件夹是否存在
            if (!Directory.Exists(root))
            {
                //不存在 创建Download文件夹
                Directory.CreateDirectory(root);
            }

            //压缩包路径
            string zipPath = root + "\\支付宝账单.zip";
            //文件路径
            string filePath = "";

            //遍历天数
            do
            {
                #region 账单参数
                //bill_type格式:trade指商户基于支付宝交易收单的业务账单;signcustomer是指基于商户支付宝余额收入及支出等资金变动的帐务账单
                //bill_date格式:2018-09-13
                string bill_date = beginDate.ToString("yyyy-MM-dd");

                request.BizContent = "{" +
                                     "\"bill_type\":\"" + bill_type + "\"," +
                                     "\"bill_date\":\"" + bill_date + "\"" +
                                     "}";
                #endregion

                //获取已授权商户集合
                IList <Store> storeList = storeDao.GetOauthList().Where(o => string.IsNullOrEmpty(o.ZFBMch_Id) == false).ToList();

                //遍历商户
                foreach (var store in storeList)
                {
                    //appAuthToken:某个商户的appAuthToken(201809BBb2b88d5c11f348b2a92be0c394b05A11)
                    string appAuthToken = store.app_auth_token;
                    AlipayDataDataserviceBillDownloadurlQueryResponse response = client.Execute(request, "", appAuthToken);

                    if (response.Msg == "Success")
                    {
                        #region  载账单
                        try
                        {
                            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(response.BillDownloadUrl);
                            req.ServicePoint.Expect100Continue = false;
                            req.Method    = "GET";
                            req.KeepAlive = true;
                            //req.ContentType = "zip";// "image/png";
                            using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse())
                            {
                                using (Stream reader = rsp.GetResponseStream())
                                {
                                    using (FileStream writer = new FileStream(zipPath, FileMode.OpenOrCreate, FileAccess.Write))
                                    {
                                        byte[] buff = new byte[512];
                                        int    c    = 0; //实际读取的字节数
                                        while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                                        {
                                            writer.Write(buff, 0, c);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            errorLogDao.SaveErrorLog("支付宝对账单下载出错:" + ex.Message);
                        }
                        #endregion

                        #region 解压账单
                        ZipInputStream zipStream = new ZipInputStream(File.Open(zipPath, FileMode.Open));
                        ZipEntry       entry     = zipStream.GetNextEntry();

                        while (entry != null)
                        {
                            if (!entry.IsFile)
                            {
                                continue;
                            }

                            //不解压汇总压缩包
                            if (entry.Name.Contains("汇总"))
                            {
                                //读取下一个压缩包
                                entry = zipStream.GetNextEntry();
                                continue;
                            }

                            //20885225452401150156_20180912_业务明细.csv
                            //20885225452401150156_20180912_业务明细(汇总).csv
                            filePath = Environment.CurrentDirectory.Replace("\\bin\\Debug", "") + "\\Download\\" + entry.Name;
                            //解压后的文件
                            FileStream writer = File.Create(filePath);

                            int    bufferSize = 2048; //缓冲区大小
                            int    readCount  = 0;    //读入缓冲区的实际字节
                            byte[] buffer     = new byte[bufferSize];
                            readCount = zipStream.Read(buffer, 0, bufferSize);
                            while (readCount > 0)
                            {
                                writer.Write(buffer, 0, readCount);
                                readCount = zipStream.Read(buffer, 0, bufferSize);
                            }

                            writer.Close();
                            writer.Dispose();

                            //读取下一个压缩包
                            entry = zipStream.GetNextEntry();
                        }

                        zipStream.Close();
                        zipStream.Dispose();
                        #endregion

                        #region 遍历账单
                        StreamReader sr        = new StreamReader(filePath, Encoding.GetEncoding("gb2312"));
                        string       line      = ""; //每行内容
                        int          lineIndex = 0;  //第一行为标题
                        int          count     = 0;  //总行数
                        int          maxCount  = 0;  //所需读取数据数
                        int          maxIndex  = 0;  //所属读取索引数
                        ZFBAccount   entity    = null;

                        #region 计算读取数
                        while (line != null)
                        {
                            line = sr.ReadLine();
                            count++;
                        }

                        //所需读取数据数
                        maxCount = count - 10;
                        //所属读取索引数
                        maxIndex = count - 5;
                        //重置
                        line = "";
                        //关闭流
                        sr.Close();
                        #endregion

                        #region 校验是否需要保存数据

                        #region 过滤条件
                        List <DataFilter> filters = new List <DataFilter>();
                        //匹配商户号
                        filters.Add(new DataFilter {
                            comparison = "eq", field = "MchId", type = "string", value = store.ZFBMch_Id
                        });
                        //大于等于起始日期
                        filters.Add(new DataFilter {
                            comparison = "gteq", field = "PayTime", type = "date", value = beginDate.ToString("yyyy-MM-dd 00:00:00")
                        });
                        //小于等于起始日期
                        filters.Add(new DataFilter {
                            comparison = "lteq", field = "PayTime", type = "date", value = beginDate.ToString("yyyy-MM-dd 23:59:59")
                        });
                        #endregion

                        //校验是否需要保存支付宝账单
                        bool isSave = ZFBAccountDao.CheckIsSave(filters, maxCount);

                        if (isSave)
                        {
                            //需要保存
                            //删除历史数据
                            ZFBAccountDao.Delete(filters);
                        }
                        else
                        {
                            //不需要保存
                            //换下一个商家
                            continue;
                        }

                        #endregion

                        sr = new StreamReader(filePath, Encoding.GetEncoding("gb2312"));
                        //商户号
                        string mchId = "";

                        //支付宝交易号,商户订单号,业务类型,商品名称,创建时间,完成时间,门店编号,门店名称,操作员,终端号,对方账户,订单金额(元),商家实收(元),支付宝红包(元),集分宝(元),支付宝优惠(元),商家优惠(元),券核销金额(元),券名称,商家红包消费金额(元),卡消费金额(元),退款批次号/请求号,服务费(元),分润(元),备注
                        while (line != null && lineIndex < maxIndex)
                        {
                            line = sr.ReadLine();

                            #region 读取商户号行
                            if (lineIndex == 1)
                            {
                                //#账号:[20885225452401150156] 处理后得到 2088522545240115
                                mchId = line.Split('[')[1].Substring(0, 16);
                            }
                            #endregion

                            #region 读取数据行,保存账单
                            if (lineIndex > 4 && line != null)
                            {
                                string[] accounts = line.Split(',');

                                //创建新账单
                                entity = new ZFBAccount
                                {
                                    MchId           = mchId,                                  //商户号
                                    OrderNo         = accounts[0].Trim(),                     //支付宝交易号
                                    MchOrderNo      = accounts[1].Trim(),                     //商户订单号
                                    PayType         = accounts[2].Trim(),                     //业务类型
                                    GoodsName       = accounts[3].Trim(),                     //商品名称
                                    CreateTime      = Convert.ToDateTime(accounts[4].Trim()), //创建时间
                                    PayTime         = Convert.ToDateTime(accounts[5].Trim()), //完成时间
                                    StoreNo         = accounts[6].Trim(),                     //门店编号
                                    StoreName       = accounts[7].Trim(),                     //门店名称
                                    Handler         = accounts[8].Trim(),                     //操作员
                                    DeviceId        = accounts[9].Trim(),                     //终端号
                                    PayUser         = accounts[10].Trim(),                    //对方账户
                                    Total           = Convert.ToDecimal(accounts[11].Trim()), //订单金额
                                    DiscountsTotal  = Convert.ToDecimal(accounts[12].Trim()), //商家实收(元)
                                    ZFB_RedPacket   = Convert.ToDecimal(accounts[13].Trim()), //支付宝红包(元)
                                    SetPoints       = Convert.ToDecimal(accounts[14].Trim()), //集分宝(元)
                                    ZFB_Discounts   = Convert.ToDecimal(accounts[15].Trim()), //支付宝优惠(元)
                                    Store_Discounts = Convert.ToDecimal(accounts[16].Trim()), //商家优惠(元)
                                    CouponPrice     = Convert.ToDecimal(accounts[17].Trim()), //券核销金额(元)
                                    CouponName      = accounts[18].Trim(),                    //券名称
                                    Store_RedPacket = Convert.ToDecimal(accounts[19].Trim()), //商家红包消费金额(元)
                                    CardPrice       = Convert.ToDecimal(accounts[20].Trim()), //卡消费金额(元)
                                    RefundOrderNo   = accounts[21].Trim(),                    //退款批次号/请求号
                                    ServicePrice    = Convert.ToDecimal(accounts[22].Trim()), //服务费(元)
                                    SharePrice      = Convert.ToDecimal(accounts[23].Trim()), //分润(元)
                                    Remark          = accounts[24].Trim()                     //备注
                                };

                                //保存账单
                                ZFBAccountDao.Stateless_Insert(entity);
                            }
                            #endregion

                            lineIndex++;
                        }
                        //关闭流
                        sr.Close();
                        #endregion

                        #region  除文件
                        //删除文件
                        File.Delete(filePath);

                        //删除压缩包
                        File.Delete(zipPath);
                        #endregion
                    }
                }

                //增加天数
                beginDate = beginDate.AddDays(1);
            } while (beginDate <= endDate);
        }
Example #9
0
        public TexturePackEntity(string FileName)
        {
            Input = new ZipInputStream(File.OpenRead(FileName));
            ZipEntry entity;

            byte[] data = new byte[2048];
            int    size;

            while ((entity = Input.GetNextEntry()) != null)
            {
                switch (entity.Name)
                {
                case "pack.mcmeta":
                    JavaScriptSerializer PackSerializer = new JavaScriptSerializer();
                    MemoryStream         ms             = new MemoryStream();
                    while (true)
                    {
                        size = Input.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            ms.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    ms.Position = 0;
                    StreamReader sr  = new StreamReader(ms);
                    var          tmp = PackSerializer.Deserialize <TextureInfo>(sr.ReadToEnd());
                    textureInfo.pack = tmp.pack;
                    break;

                case "pack.png":
                    while (true)
                    {
                        size = Input.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            textureInfo.Logo.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;

                case @"assets/minecraft/textures/gui/options_background.png":
                    while (true)
                    {
                        size = Input.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            GuiBackground.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;

                case @"assets/minecraft/textures/gui/widgets.png":
                    while (true)
                    {
                        size = Input.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            GuiWidgets.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    break;

                default:
                    continue;
                }
            }
            if (GuiWidgets.Length != 0)
            {
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = this.GuiBackground;
                bitmap.EndInit();
                GuiButton.Source = bitmap;
                RectangleGeometry clip = new RectangleGeometry(new System.Windows.Rect(0, bitmap.Height * 0.2578125, bitmap.Width * 0.78125, bitmap.Height * 0.0703125));
                GuiButton.Clip = clip;
            }
        }
Example #10
0
        private void analyzeFile(string filePath, string fileName)
        {
            //解压文件
            ZipInputStream s = new ZipInputStream(File.OpenRead(filePath + "\\" + fileName));
            ZipEntry       theEntry;

            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(filePath);
                fileName = Path.GetFileName(theEntry.Name);

                //生成解压目录
                Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    //解压文件到指定的目录
                    FileStream streamWriter = File.Create(filePath + theEntry.Name);

                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            s.Close();

            //遍历解压之后目录下的所有文件,对流水文件分析
            foreach (string file in Directory.GetFiles(filePath))
            {
                fileName = file.Substring(filePath.Length);
                List <Dictionary <int, string> > list = null;

                if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 3) == "ZM_")
                {
                    list = parseZMFile(file);
                }
                else if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 4) == "ZME_")
                {
                    list = parseZMEFile(file);
                }

                if (list != null)
                {
                    Response.Write(fileName + "部分参数读取(读取方式请参考Form_7_2_FileTransfer的代码):<br>\n");
                    Response.Write("<table border='1'>\n");
                    Response.Write("<tr><th>txnType</th><th>orderId</th><th>txnTime(MMDDhhmmss)</th></tr>");
                    foreach (Dictionary <int, string> dic in list)
                    {
                        //TODO 参看https://open.unionpay.com/ajweb/help?id=258,根据编号获取即可,例如订单号12、交易类型20。
                        //具体写代码时可能边读文件边修改数据库性能会更好,请注意自行根据parseFile中的读取方法修改。
                        Response.Write("<tr>\n");
                        Response.Write("<td>" + dic[20] + "</td>\n"); //txnType
                        Response.Write("<td>" + dic[12] + "</td>\n"); //orderId
                        Response.Write("<td>" + dic[5] + "</td>\n");  //txnTime不带年份
                        Response.Write("</tr>\n");
                    }
                    Response.Write("</table>\n");
                }
            }
        }
        private String UnZipFile(string file, string target)
        {
            String p = Path.GetFileName(file);

            if (p.StartsWith("DHU") == false)
            {
                return("");
            }
            //先得到版本号
            string[] v = file.Split('_');
            if (v.Length == 1)
            {
                return("");
            }
            string version = file.Substring(file.LastIndexOf('_') + 1);

            version = version.Replace(".zip", "");

            string curVersion = GetCurVersion();

            Util.Log("当前的版本号为:" + curVersion);

            if (curVersion.CompareTo(version) == 1)
            {
                //不小于
                Util.Log("当前的版本号大于" + version + ",返回");
                return("");
            }

            Util.Log("解压文件:" + file);
            ZipInputStream ssss = new ZipInputStream(File.OpenRead(file));
            ZipEntry       theEntry;

            try
            {
                while ((theEntry = ssss.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(target);
                    string fileName      = Path.GetFileName(theEntry.Name);
                    Util.Log("开始解压内容:" + fileName);
                    ////生成解压目录
                    //Directory.CreateDirectory(directoryName);
                    if (fileName != String.Empty)
                    {
                        //解压文件到指定的目录
                        FileStream streamWriter = null;
                        string     filename     = target + "\\" + theEntry.Name;
                        int        index        = 0;
                        while (index < 10)
                        {
                            try
                            {
                                streamWriter = File.Create(filename);
                                break;
                            }
                            catch (Exception ex2)
                            {
                                Util.Log("exception 解压文件" + filename + "时发生错误:" + ex2.Message);
                                index += 1;
                                Util.Log("index=" + index + " 睡眠500毫秒");
                                System.Threading.Thread.Sleep(500);
                            }
                        }

                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = ssss.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                if (streamWriter != null)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (streamWriter != null)
                        {
                            streamWriter.Close();
                            Util.Log("成功解压内容:" + fileName);
                        }
                    }
                    else if (theEntry.Name.EndsWith("/"))
                    {
                        string folder = target + "//" + theEntry.Name;
                        if (Directory.Exists(folder) == false)
                        {
                            //不存在该目录
                            Directory.CreateDirectory(folder);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //解压出错
                Util.Log("解压失败:" + e.Message);
            }
            ssss.Close();
            return(version);
        }
Example #12
0
        internal ZipPackage(Stream stream)
        {
            bool hasContentTypeXml = false;

            if (stream == null || stream.Length == 0)
            {
                AddNew();
            }
            else
            {
                var rels = new Dictionary <string, string>();
                stream.Seek(0, SeekOrigin.Begin);
                using (ZipInputStream zip = new ZipInputStream(stream))
                {
                    var e = zip.GetNextEntry();
                    while (e != null)
                    {
                        if (e.UncompressedSize > 0)
                        {
                            var b    = new byte[e.UncompressedSize];
                            var size = zip.Read(b, 0, (int)e.UncompressedSize);
                            if (e.FileName.ToLower() == "[content_types].xml")
                            {
                                AddContentTypes(Encoding.UTF8.GetString(b));
                                hasContentTypeXml = true;
                            }
                            else if (e.FileName.ToLower() == "_rels/.rels")
                            {
                                ReadRelation(Encoding.UTF8.GetString(b), "");
                            }
                            else
                            {
                                if (e.FileName.ToLower().EndsWith(".rels"))
                                {
                                    rels.Add(GetUriKey(e.FileName), Encoding.UTF8.GetString(b));
                                }
                                else
                                {
                                    var part = new ZipPackagePart(this, e);
                                    part.Stream = new MemoryStream();
                                    part.Stream.Write(b, 0, b.Length);
                                    Parts.Add(GetUriKey(e.FileName), part);
                                }
                            }
                        }
                        else
                        {
                        }
                        e = zip.GetNextEntry();
                    }

                    foreach (var p in Parts)
                    {
                        FileInfo fi      = new FileInfo(p.Key);
                        string   relFile = string.Format("{0}_rels/{1}.rels", p.Key.Substring(0, p.Key.Length - fi.Name.Length), fi.Name);
                        if (rels.ContainsKey(relFile))
                        {
                            p.Value.ReadRelation(rels[relFile], p.Value.Uri.OriginalString);
                        }
                        if (_contentTypes.ContainsKey(p.Key))
                        {
                            p.Value.ContentType = _contentTypes[p.Key].Name;
                        }
                        else if (fi.Extension.Length > 1 && _contentTypes.ContainsKey(fi.Extension.Substring(1)))
                        {
                            p.Value.ContentType = _contentTypes[fi.Extension.Substring(1)].Name;
                        }
                    }
                    if (!hasContentTypeXml)
                    {
                        throw (new FileFormatException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor."));
                    }
                    if (!hasContentTypeXml)
                    {
                        throw (new FileFormatException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor."));
                    }
                    zip.Close();
                }
            }
        }
Example #13
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="_depositPath">压缩文件路径</param>
        /// <param name="_floderPath">解压的路径</param>
        /// <returns></returns>
        public bool DeCompressionZip(string _depositPath, string _floderPath)
        {
            bool       result = true;
            FileStream fs     = null;

            try
            {
                ZipInputStream InpStream = new ZipInputStream(File.OpenRead(_depositPath));
                ZipEntry       ze        = InpStream.GetNextEntry(); //获取压缩文件中的每一个文件
                Directory.CreateDirectory(_floderPath);              //创建解压文件夹
                while (ze != null)                                   //如果解压完ze则是null
                {
                    if (ze.IsFile)                                   //压缩zipINputStream里面存的都是文件。带文件夹的文件名字是文件夹\\文件名
                    {
                        string[] strs = ze.Name.Split('\\');         //如果文件名中包含’\\‘则表明有文件夹
                        if (strs.Length > 1)
                        {
                            //两层循环用于一层一层创建文件夹
                            for (int i = 0; i < strs.Length - 1; i++)
                            {
                                string floderPath = _floderPath;
                                for (int j = 0; j < i; j++)
                                {
                                    floderPath = floderPath + "\\" + strs[j];
                                }
                                floderPath = floderPath + "\\" + strs[i];
                                Directory.CreateDirectory(floderPath);
                            }
                        }
                        fs = new FileStream(_floderPath + "\\" + ze.Name, FileMode.OpenOrCreate, FileAccess.Write);//创建文件
                        //循环读取文件到文件流中
                        while (true)
                        {
                            byte[] bts = new byte[1024];
                            int    i   = InpStream.Read(bts, 0, bts.Length);
                            if (i > 0)
                            {
                                fs.Write(bts, 0, i);
                            }
                            else
                            {
                                fs.Flush();
                                fs.Close();
                                break;
                            }
                        }
                    }
                    ze = InpStream.GetNextEntry();
                }
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                errorMsg = ex.Message;
                result   = false;
            }
            return(result);
        }
Example #14
0
        public async Task <JsonResult> UploadFiles(IFormFile Zip, IFormFile ProductsExcelFile)
        {
            var    webRoot  = _env.WebRootPath;
            string TempPath = Path.Combine(webRoot, "Uploads/Product/");

            // upload zip file
            #region upload zip file

            string ZipFileName = TempPath + Zip.FileName;
            var    photos      = new Dictionary <string, PhotoStruct>();
            if (Path.GetExtension(ZipFileName).Equals(".zip"))
            {
                try
                {
                    using (var s = new ZipInputStream(Zip.OpenReadStream()))
                    {
                        ZipEntry theEntry;
                        while ((theEntry = s.GetNextEntry()) != null)
                        {
                            string fileName = Path.GetFileName(theEntry.Name);

                            // create directory
                            if (fileName != String.Empty)
                            {
                                if (fileName.IndexOfAny(@"!@#$%^*/~\".ToCharArray()) > 0)
                                {
                                    continue;
                                }
                                var size      = theEntry.Size;
                                var binary    = new byte[size];
                                int readBytes = 0;
                                while (readBytes < size)
                                {
                                    var read = s.Read(binary, readBytes, Convert.ToInt32(size));
                                    readBytes += read;
                                }
                                var ext      = Path.GetExtension(fileName);
                                var guidName = Guid.NewGuid().ToString() + ext;
                                photos.Add(fileName, new PhotoStruct(ref binary, guidName));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return(Json(new { Ok = false, message = "Empty File" }));
                }
            }
            else
            {
                // ViewBag.noticZipFileUpload = "Empty File";
                return(Json(new { Ok = false, message = "Empty File" }));
            }

            #endregion

            // upload Sheet
            #region upload sheet

            if (ProductsExcelFile.Length > 0 && photos.Count > 0)
            {
                // extract only the filename
                var    fileName = Path.GetFileName(ProductsExcelFile.FileName);
                string ext      = Path.GetExtension(ProductsExcelFile.FileName);

                string NewFileName = "Products_" + DateTime.Now.ToShortDateString().Replace("/", "-") + "-" + DateTime.Now.ToShortTimeString().Replace(":", "-").Replace(" ", "-") + ext;

                fileName = NewFileName;

                var path = Path.Combine(TempPath, fileName);


                using (var wb = new XLWorkbook(ProductsExcelFile.OpenReadStream()))
                {
                    IXLWorksheet sheet;
                    try
                    {
                        wb.SaveAs(path);
                        wb.TryGetWorksheet("Sheet1", out sheet);
                        if (sheet != null)
                        {
                            // get last row
                            string lastrow = sheet.LastRowUsed().RangeAddress.FirstAddress.ToString();
                            lastrow = lastrow.Remove(0, 1);
                            var rowCount = int.Parse(lastrow);
                            // 2 beacuse header
                            var rowRange  = sheet.Rows(2, rowCount).ToList();
                            var rowsCount = rowRange.Count();
                            // to get first row
                            var firstrowRange = sheet.Rows(1, 2).ToList();
                            var FirstRowcols  = firstrowRange[0].Cells().ToList();


                            if (
                                FirstRowcols[0].Value.ToString() == "Product Name" &&
                                FirstRowcols[1].Value.ToString() == "Code" &&
                                FirstRowcols[2].Value.ToString() == "Image Name" &&
                                FirstRowcols[3].Value.ToString() == "Department" &&
                                FirstRowcols[4].Value.ToString() == "Amount")
                            {
                                if (rowsCount < 1000)
                                {
                                    List <Product>      productList = new List <Product>();
                                    List <ProductError> lstErr      = new List <ProductError>()
                                    {
                                    };


                                    var AllProduct = UnitOfWork.ProductBL.GetAllProductList()
                                                     .Where(p => p.IsActive == true)
                                                     .ToList();


                                    for (int i = 0; i < rowsCount; i++)

                                    {
                                        Product      product = new Product();
                                        ProductError err     = new ProductError();
                                        string       reason  = string.Empty;

                                        var cols = rowRange.ElementAt(i).Cells().ToList();
                                        if (
                                            !string.IsNullOrEmpty(cols[0].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[1].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[2].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[3].Value.ToString()) &&
                                            !string.IsNullOrEmpty(cols[4].Value.ToString())

                                            )
                                        {
                                            product.InventoryQnty = Convert.ToDecimal(cols[4].Value);
                                            product.IsActive      = true;
                                            product.CreatedDate   = DateTime.Now;
                                            product.CreatedBy     = LoggedUserId;

                                            // Department
                                            var department = AllProduct.Where(p => p.Department.Name.ToLower() == (string)cols[3].Value.ToString().ToLower())
                                                             .FirstOrDefault();
                                            if (department != null)
                                            {
                                                product.DepartmentId = department.DepartmentId;
                                            }
                                            else
                                            {
                                                reason += "Department not exist, ";
                                            }


                                            // end
                                            if (department != null)
                                            {
                                                // check unique name
                                                if (AllProduct.Where(p => p.DepartmentId == department.DepartmentId && p.Name == cols.ElementAt(0).Value.ToString()).FirstOrDefault() == null)
                                                {
                                                    product.Name = cols[0].Value.ToString();
                                                }
                                                else
                                                {
                                                    reason += "Name already exist, ";
                                                }
                                                //Code
                                                if (AllProduct.Where(p => p.DepartmentId == department.DepartmentId && p.Code == cols[1].Value.ToString()).FirstOrDefault() == null)
                                                {
                                                    product.Code = cols[1].Value.ToString();
                                                }
                                                else
                                                {
                                                    reason += "Code already exist, ";
                                                }
                                            }


                                            //End


                                            // image
                                            string imageName = cols[2].Value.ToString();
                                            if (photos.ContainsKey(imageName))
                                            {
                                                var photoStruct = photos[imageName];
                                                var imagePath   = Path.Combine("Uploads", "Product", photoStruct.GuidName);
                                                var fullpath    = Path.Combine(webRoot, imagePath);
                                                try
                                                {
                                                    if (!System.IO.File.Exists(fullpath))
                                                    {
                                                        await System.IO.File.WriteAllBytesAsync(fullpath, photoStruct.Binary);
                                                    }
                                                    product.Image = @"\" + imagePath;
                                                }
                                                catch (Exception ex)
                                                {
                                                    reason += "Failed to save image, ";
                                                }
                                            }
                                            else
                                            {
                                                reason += "Image doesn't exist in zip file, ";
                                            }
                                            // end
                                        }
                                        else if (string.IsNullOrEmpty(cols[0].ToString()) || string.IsNullOrEmpty(cols[1].ToString()) || string.IsNullOrEmpty(cols[2].ToString()) || string.IsNullOrEmpty(cols[3].ToString()))
                                        {
                                            reason += "Empty Field, ";
                                        }

                                        if (string.IsNullOrEmpty(reason))
                                        {
                                            if (!string.IsNullOrEmpty(product.Name) && !string.IsNullOrEmpty(product.Code))
                                            {
                                                productList.Add(product);
                                            }
                                        }
                                        else
                                        {
                                            err.Name   = cols[0].Value.ToString();
                                            err.Code   = cols[1].Value.ToString();
                                            err.Image  = cols[3].Value.ToString();
                                            err.Reason = reason;
                                            lstErr.Add(err);
                                        }
                                    }

                                    UnitOfWork.ProductBL.AddRange(productList);
                                    if (UnitOfWork.Complete(LoggedUserId) > 0)
                                    {
                                        return(Json(new { Ok = true, Message = ApplicationMessages.SaveSuccess, err = lstErr }));
                                    }
                                    else
                                    {
                                        return(Json(new { Ok = false, Message = "Failed to import products", err = lstErr }));
                                    }
                                }
                            }
                            else
                            {
                                return(Json(new { Ok = false, Message = "Please download Tempelte", temp = true }));
                            }
                        }
                    }

                    catch (Exception ex)
                    {
                        return(Json(new { Ok = false, Message = ApplicationMessages.ErrorOccure }));
                    }
                }
            }
            return(Json(new { Ok = true }));

            #endregion
        }
Example #15
0
        public void Decompress(string srcPath, string targetPath, bool isDeleteSrc = false)
        {
            long totalSize    = GetTotalSize(srcPath); //bit
            long receivedSize = 0;                     //bit
            long time         = 0;                     //second
            long speed        = 0;                     //bit/s

            byte[] data = new byte[2048];              //readbuf
            int    size = 0;                           //read size

            PathHelper.InculdeBackslash(ref targetPath);
            PathHelper.CreateDirifnotExist(targetPath); //生成解压目录

            System.Timers.Timer m_speedTimer = new System.Timers.Timer(Convert.ToDouble(2000));
            m_speedTimer.Elapsed  += new System.Timers.ElapsedEventHandler((s, e) => GetDecompressSpeed(s, e, receivedSize, ref time, ref speed));
            m_speedTimer.AutoReset = true;

            try
            {
                using (ZipInputStream zipInStream = new ZipInputStream(File.OpenRead(srcPath)))
                {
                    m_cancelTokenSource = new CancellationTokenSource();
                    ZipEntry theEntry = null;
                    while ((theEntry = zipInStream.GetNextEntry()) != null && (!m_cancelTokenSource.IsCancellationRequested))
                    {
                        string EntryPath = targetPath + theEntry.Name;

                        if (theEntry.IsDirectory)
                        {
                            PathHelper.CreateDirifnotExist(EntryPath);
                        }
                        else
                        {
                            if (theEntry.Name != String.Empty)
                            {
                                PathHelper.CreateDirifnotExist(Path.GetDirectoryName(EntryPath));

                                using (FileStream streamWriter = File.Create(EntryPath))
                                {
                                    while (!m_cancelTokenSource.IsCancellationRequested)
                                    {
                                        if (!m_speedTimer.Enabled)
                                        {
                                            m_speedTimer.Enabled = true;
                                        }

                                        size = zipInStream.Read(data, 0, data.Length);
                                        if (size <= 0)
                                        {
                                            break;
                                        }
                                        else
                                        {
                                            receivedSize += size;
                                            int perc = Convert.ToInt32(Math.Floor((receivedSize * 100.00) / totalSize));
                                            if (perc == 100)
                                            {
                                                int s = 9 + 9;
                                            }
                                            ReportProgress(perc, srcPath, theEntry.Name, speed, totalSize, receivedSize);
                                        }

                                        streamWriter.Write(data, 0, size);
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                    }
                    zipInStream.Close();
                    m_speedTimer.Enabled = false;
                    m_speedTimer.Close();
                }
            }
            catch (Exception ex)
            {
                ReportExceptionError(ex);
                return;
            }

            if (!m_cancelTokenSource.IsCancellationRequested)
            {
                ReportFinished(srcPath);

                if (isDeleteSrc)
                {
                    File.Delete(srcPath);
                }
            }
        }
Example #16
0
        /// <summary>
        /// 解压压缩文件到指定目录
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <param name="password">密码</param>
        /// <returns>解压结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password = "")
        {
            try
            {
                if (!File.Exists(fileToUnZip))
                {
                    throw new FileNotFoundException(fileToUnZip);
                }

                if (!Directory.Exists(zipedFolder))
                {
                    Directory.CreateDirectory(zipedFolder);
                }

                using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(fileToUnZip)))
                {
                    if (!string.IsNullOrEmpty(password))
                    {
                        zipStream.Password = password;
                    }

                    ZipEntry entry = null;

                    while ((entry = zipStream.GetNextEntry()) != null)
                    {
                        if (string.IsNullOrEmpty(entry.Name))
                        {
                            continue;
                        }

                        string fileName = Path.Combine(zipedFolder, entry.Name);
                        fileName = fileName.Replace('/', '\\');

                        if (fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        string sfilePathParent = Path.GetDirectoryName(fileName);
                        if (!Directory.Exists(sfilePathParent))
                        {
                            Directory.CreateDirectory(sfilePathParent);
                        }

                        using (FileStream fs = File.Create(fileName))
                        {
                            int    size = 2048;
                            byte[] data = new byte[size];
                            while ((size = zipStream.Read(data, 0, data.Length)) > 0)
                            {
                                fs.Write(data, 0, size);
                            }
                        }
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #17
0
    /// <summary>
    /// UnZip Theme
    /// </summary>
    /// <param name="themesPath"></param>
    /// <param name="fileStream"></param>
    public void UnZip(string themesPath, Stream fileStream)
    {
        ZipInputStream s = new ZipInputStream(fileStream);
        ZipEntry theEntry = null;
        while ((theEntry = s.GetNextEntry()) != null)
        {

            string directoryName = Path.GetDirectoryName(themesPath + theEntry.Name);
            string fileName = Path.GetFileName(theEntry.Name);

            // create directory
            if (directoryName.Length > 0)
            {
                Directory.CreateDirectory(directoryName);
            }

            if (fileName != String.Empty)
            {
                using (FileStream streamWriter = File.Create(themesPath + theEntry.Name))
                {

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        s.Close();
    }
Example #18
0
 /// <summary>
 /// 解压缩目录
 /// </summary>
 /// <param name="zipDirectoryPath">压缩目录路径</param>
 /// <param name="unZipDirecotyPath">解压缩目录路径</param>
 /// <param name="password">密码</param>
 public static void DeCompress(string zipDirectoryPath, string unZipDirecotyPath, string password)
 {
     Log.Info("DeCompress-Begin");
     try
     {
         while (unZipDirecotyPath.LastIndexOf("\\", StringComparison.CurrentCultureIgnoreCase) + 1 ==
                unZipDirecotyPath.Length)                                                      //检查路径是否以"\"结尾
         {
             unZipDirecotyPath = unZipDirecotyPath.Substring(0, unZipDirecotyPath.Length - 1); //如果是则去掉末尾的"\"
             //Log.Debug("DeCompress-01");
         }
         //Log.Debug("DeCompress-02");
         using (var inputStream = new FileStream(zipDirectoryPath, FileMode.Open, FileAccess.Read))
         {
             using (var zipStream = new ZipInputStream(inputStream))
             {
                 //判断Password
                 if (!string.IsNullOrEmpty(password))
                 {
                     zipStream.Password = password;
                 }
                 ZipEntry zipEntry = null;
                 while ((zipEntry = zipStream.GetNextEntry()) != null)
                 {
                     string directoryName = Path.GetDirectoryName(zipEntry.Name);
                     string fileName      = Path.GetFileName(zipEntry.Name);
                     if (!string.IsNullOrEmpty(directoryName))
                     {
                         string directoryPath = Path.Combine(unZipDirecotyPath, directoryName);
                         if (!Directory.Exists(directoryPath))
                         {
                             Directory.CreateDirectory(directoryPath);
                         }
                     }
                     if (!string.IsNullOrEmpty(fileName))
                     {
                         //if (zipEntry.CompressedSize == 0)
                         //    break;
                         if (zipEntry.IsDirectory)//如果压缩格式为文件夹方式压缩
                         {
                             directoryName = Path.GetDirectoryName(unZipDirecotyPath + @"\" + zipEntry.Name);
                             if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
                             {
                                 Directory.CreateDirectory(directoryName);
                             }
                         }
                         else//2012-5-28修改,支持单个文件压缩时自己创建目标文件夹
                         {
                             if (!Directory.Exists(unZipDirecotyPath))
                             {
                                 Directory.CreateDirectory(unZipDirecotyPath);
                             }
                         }
                         //Log.Debug("test-def");
                         var singleFileName = unZipDirecotyPath + @"\" + zipEntry.Name;
                         FileUtil.DeleteFile(singleFileName);
                         using (var stream = new FileStream(unZipDirecotyPath + @"\" + zipEntry.Name,
                                                            FileMode.OpenOrCreate, FileAccess.Write))
                         //File.Create(unZipDirecotyPath + @"\" + zipEntry.Name))
                         {
                             while (true)
                             {
                                 var buffer = new byte[8192];
                                 int size   = zipStream.Read(buffer, 0, buffer.Length);
                                 if (size > 0)
                                 {
                                     stream.Write(buffer, 0, size);
                                 }
                                 else
                                 {
                                     break;
                                 }
                             }
                             //Log.Debug("test-hjk");
                             stream.Close();
                         }
                     }
                 }
                 zipStream.Close();
             }
             inputStream.Close();
         }
     }
     catch (IOException e)
     {
         Log.Error(e);
         throw new ApplicationException(e.Message, e);
     }
     catch (Exception e)
     {
         Log.Error(e);
         throw new ApplicationException(e.Message, e);
     }
 }
Example #19
0
    /// <summary>
    /// 功能:解压zip格式的文件。
    /// </summary>
    /// <param name="zipFilePath">压缩文件路径</param>
    /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
    /// <param name="err">出错信息</param>
    /// <returns>解压是否成功</returns>
    public static void UnZip(string zipFilePath, string unZipDir)
    {
        if (zipFilePath == string.Empty)
        {
            throw new Exception("压缩文件不能为空!");
        }
        if (!File.Exists(zipFilePath))
        {
            throw new System.IO.FileNotFoundException("压缩文件不存在!");
        }
        //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
        if (unZipDir == string.Empty)
        {
            unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
        }
        if (!unZipDir.EndsWith("/"))
        {
            unZipDir += "/";
        }
        if (!Directory.Exists(unZipDir))
        {
            Directory.CreateDirectory(unZipDir);
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
        {
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);
                if (directoryName.Length > 0)
                {
                    Directory.CreateDirectory(unZipDir + directoryName);
                }
                if (!directoryName.EndsWith("/"))
                {
                    directoryName += "/";
                }
                if (fileName != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                    {
                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
Example #20
0
 public static void UnzipResources(ZipInputStream zipStream, string destPath)
 {
     try
     {
         ZipEntry objZipEntry;
         string   LocalFileName;
         string   RelativeDir;
         string   FileNamePath;
         objZipEntry = zipStream.GetNextEntry();
         while (objZipEntry != null)
         {
             LocalFileName = objZipEntry.Name;
             RelativeDir   = Path.GetDirectoryName(objZipEntry.Name);
             if ((RelativeDir != string.Empty) && (!Directory.Exists(Path.Combine(destPath, RelativeDir))))
             {
                 Directory.CreateDirectory(Path.Combine(destPath, RelativeDir));
             }
             if ((!objZipEntry.IsDirectory) && (!String.IsNullOrEmpty(LocalFileName)))
             {
                 FileNamePath = Path.Combine(destPath, LocalFileName).Replace("/", "\\");
                 try
                 {
                     if (File.Exists(FileNamePath))
                     {
                         File.SetAttributes(FileNamePath, FileAttributes.Normal);
                         File.Delete(FileNamePath);
                     }
                     FileStream objFileStream = null;
                     try
                     {
                         objFileStream = File.Create(FileNamePath);
                         int intSize = 2048;
                         var arrData = new byte[2048];
                         intSize = zipStream.Read(arrData, 0, arrData.Length);
                         while (intSize > 0)
                         {
                             objFileStream.Write(arrData, 0, intSize);
                             intSize = zipStream.Read(arrData, 0, arrData.Length);
                         }
                     }
                     finally
                     {
                         if (objFileStream != null)
                         {
                             objFileStream.Close();
                             objFileStream.Dispose();
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     //   DnnLog.Error(ex);
                 }
             }
             objZipEntry = zipStream.GetNextEntry();
         }
     }
     finally
     {
         if (zipStream != null)
         {
             zipStream.Close();
             zipStream.Dispose();
         }
     }
 }
Example #21
0
        private string Descomprimir(string directorio, string zipFic = "")
        {
            string RutaArchivo = string.Empty;

            try
            {
                if (!zipFic.ToLower().EndsWith(".zip"))
                {
                    zipFic = Directory.GetFiles(zipFic, "*.zip")[0];
                }
                if (directorio == "")
                {
                    directorio = ".";
                }
                ZipInputStream z = new ZipInputStream(File.OpenRead(directorio + @"\" + zipFic));
                ZipEntry       theEntry;
                do
                {
                    theEntry = z.GetNextEntry();
                    if (theEntry != null)
                    {
                        string fileName = directorio + @"\" + Path.GetFileName(theEntry.Name);
                        if (!Directory.Exists(fileName))
                        {
                            if (Path.GetExtension(fileName).ToString().ToUpper() == ".XML")
                            {
                                RutaArchivo = fileName;
                                FileStream streamWriter;
                                try
                                {
                                    streamWriter = File.Create(fileName);
                                }
                                catch (DirectoryNotFoundException ex)
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                                    streamWriter = File.Create(fileName);
                                }
                                //
                                int    size;
                                byte[] data = new byte[2049];
                                do
                                {
                                    size = z.Read(data, 0, data.Length);
                                    if ((size > 0))
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }while (true);
                                streamWriter.Close();
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }while (true);
                z.Close();
                return(RutaArchivo);
            }
            catch (Exception ex)
            {
                //Log.Error(ex.Message, excepcion: ex);
            }
            return("");
        }
Example #22
0
        protected override IEnumerator IDownloadZip(string ip, string hostName, rRes data)
        {
            mLogger.Log("start download -> " + data.FileName);

            //設置下載路徑
            string path = GetLocation(ip, hostName) + data.Path + data.FileName;

            using (WWW bundle = new WWW(path))
            {
                yield return(bundle);

                //檢查下載錯誤訊息
                if (bundle.error != null)
                {
                    mStatus = eStatus.Error;
                    mOnError.InvokeGracefully(bundle.error);
                    mLogger.Log(bundle.error);
                    yield break;
                }

                //檢查是否下載完成
                if (bundle.isDone == true)
                {
                    //設置存檔路徑
                    string sPath = TinyContext.Instance.DataPath + data.Path;
                    string sName = data.FileName;
                    TFile.Save(sPath, sName, bundle.bytes);

                    using (FileStream fileStream = new FileStream(sPath + sName, FileMode.Open, FileAccess.Read))
                    {
                        using (ZipInputStream zipInputStream = new ZipInputStream(fileStream))
                        {
                            ZipEntry zipEntry;

                            // 逐一取出壓縮檔內的檔案(解壓縮)
                            while ((zipEntry = zipInputStream.GetNextEntry()) != null)
                            {
                                string zPath = TinyContext.Instance.DataPath + data.Path + zipEntry.Name;

                                //檢查是否存在舊檔案
                                if (File.Exists(zPath) == true)
                                {
                                    File.Delete(zPath);
                                }

                                mLogger.Log(zipEntry.Name);

                                using (FileStream fs = File.Create(zPath))
                                {
                                    while (true)
                                    {
                                        int size = zipInputStream.Read(mBuffer, 0, mBuffer.Length);

                                        if (size > 0)
                                        {
                                            fs.Write(mBuffer, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }

                                        yield return(null);
                                    }
                                    fs.Close();
                                }
                                yield return(null);
                            }
                            zipInputStream.Close();
                        }
                        fileStream.Close();
                    }

#if !UNITY_TVOS || UNITY_EDITOR
                    File.Delete(sPath + sName);
#endif
                }
                else
                {
                    mStatus = eStatus.Error;
                    mOnError.InvokeGracefully(string.Format("下載失敗 -> {0}", bundle.url));
                    mLogger.Log(string.Format("下載失敗 -> {0}", bundle.url));
                }
            }
            mLogger.Log("end download -> " + data.FileName);
            Resources.UnloadUnusedAssets();
        }
Example #23
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">解压目标存放目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }
            ZipInputStream s        = null;
            ZipEntry       theEntry = null;
            string         fileName;
            FileStream     streamWriter = null;

            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        streamWriter = File.Create(fileName);
                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
Example #24
0
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        public void UnZip()
        {
            string FileToUpZip = UpdateModel.UpdateFilePath;
            string ZipedFolder = Application.StartupPath;
            string Password    = "";

            //如果文件不存在就return
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            //如果目录不创建则创建
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }

            ZipInputStream s        = null;
            ZipEntry       theEntry = null;

            string     fileName;
            FileStream streamWriter = null;

            try
            {
                FileStream fs = File.OpenRead(FileToUpZip);
                this.Invoke((UpdatePgBar) delegate(int value) { pgBarUnZip.Maximum = value; }, (int)fs.Length / 1024);
                s          = new ZipInputStream(fs);
                s.Password = Password;
                long count = 0;//计算已解压的文件总大小
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        ///判断文件路径是否是文件夹
                        if (fileName.EndsWith("/") || fileName.EndsWith("//"))
                        {
                            Directory.CreateDirectory(fileName);
                            this.Invoke((AddLogDelegate) delegate(string text) { AddLog(text); }, "正在创建文件夹:" + theEntry.Name);
                            continue;
                        }
                        this.Invoke((AddLogDelegate) delegate(string text) { AddLog(text); }, "正在解压文件:" + theEntry.Name);
                        streamWriter = File.Create(fileName);
                        int    size = 102400;
                        byte[] data = new byte[102400];
                        while (true)
                        {
                            size   = s.Read(data, 0, data.Length);
                            count += size;
                            this.Invoke((UpdatePgBar) delegate(int value)
                            {
                                if (value < pgBarUnZip.Maximum)
                                {
                                    pgBarUnZip.Value = value;
                                }
                            }, (Int32)count / 1024);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            //解压完成 进行下一步 退出更新程序或者执行脚本
            if (!string.IsNullOrEmpty(UpdateModel.ScriptUrl))
            {
                this.Invoke((UpdatePgBar) delegate(int value)
                {
                    FrmCmd frmCmd = new FrmCmd();
                    frmCmd.Show();
                    this.Hide();
                }, 0);
            }
            else
            {
                DirectoryInfo directoryInfo = new DirectoryInfo("Update");
                directoryInfo.Delete(true);
                Process.Start(UpdateModel.Start + ".exe");
                Environment.Exit(0);
            }
        }
Example #25
0
    /// <summary>
    /// 解压Zip包
    /// </summary>
    /// <param name="_inputStream">Zip包输入流</param>
    /// <param name="_outputPath">解压输出路径</param>
    /// <param name="_password">解压密码</param>
    /// <param name="_unzipCallback">UnzipCallback对象,负责回调</param>
    /// <returns></returns>
    public static bool UnzipFile(Stream _inputStream, string _outputPath, string _password = null, UnzipCallback _unzipCallback = null)
    {
        if ((null == _inputStream) || string.IsNullOrEmpty(_outputPath))
        {
            if (null != _unzipCallback)
            {
                _unzipCallback.OnFinished(false);
            }

            return(false);
        }

        // 创建文件目录
        if (!Directory.Exists(_outputPath))
        {
            Directory.CreateDirectory(_outputPath);
        }

        // 解压Zip包
        ZipEntry entry = null;

        using (ZipInputStream zipInputStream = new ZipInputStream(_inputStream))
        {
            if (!string.IsNullOrEmpty(_password))
            {
                zipInputStream.Password = _password;
            }

            while (null != (entry = zipInputStream.GetNextEntry()))
            {
                if (string.IsNullOrEmpty(entry.Name))
                {
                    continue;
                }

                if ((null != _unzipCallback) && !_unzipCallback.OnPreUnzip(entry))
                {
                    continue;    // 过滤
                }
                string filePathName = Path.Combine(_outputPath, entry.Name);

                // 创建文件目录
                if (entry.IsDirectory)
                {
                    Directory.CreateDirectory(filePathName);
                    continue;
                }

                // 写入文件
                try
                {
                    using (FileStream fileStream = File.Create(filePathName))
                    {
                        byte[] bytes = new byte[1024];
                        while (true)
                        {
                            int count = zipInputStream.Read(bytes, 0, bytes.Length);
                            if (count > 0)
                            {
                                fileStream.Write(bytes, 0, count);
                            }
                            else
                            {
                                if (null != _unzipCallback)
                                {
                                    _unzipCallback.OnPostUnzip(entry);
                                }

                                break;
                            }
                        }
                    }
                }
                catch (System.Exception _e)
                {
                    Debug.LogError("[ZipUtility.UnzipFile]: " + _e.ToString());

                    if (null != _unzipCallback)
                    {
                        _unzipCallback.OnFinished(false);
                    }

                    return(false);
                }
            }
        }

        if (null != _unzipCallback)
        {
            _unzipCallback.OnFinished(true);
        }

        return(true);
    }
Example #26
0
        private static void LoadDLLs(bool plugins = false)
        {
            string searchdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, (plugins ? "Plugins" : "Mods"));

            if (!Directory.Exists(searchdir))
            {
                Directory.CreateDirectory(searchdir);
            }
            else
            {
                // DLL
                string[] files = Directory.GetFiles(searchdir, "*.dll");
                if (files.Length > 0)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        string file = files[i];
                        if (!string.IsNullOrEmpty(file))
                        {
                            if (plugins)
                            {
                                if ((Imports.IsDevPluginsOnly() && !file.EndsWith("-dev.dll")) || (!Imports.IsDevPluginsOnly() && file.EndsWith("-dev.dll")))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if ((Imports.IsDevModsOnly() && !file.EndsWith("-dev.dll")) || (!Imports.IsDevModsOnly() && file.EndsWith("-dev.dll")))
                                {
                                    continue;
                                }
                            }
                            try
                            {
                                LoadAssembly(File.ReadAllBytes(file), plugins, file);
                            }
                            catch (Exception e)
                            {
                                MelonModLogger.LogError("Unable to load " + file + ":\n" + e.ToString());
                                MelonModLogger.Log("------------------------------");
                            }
                        }
                    }
                }

                // ZIP
                string[] zippedFiles = Directory.GetFiles(searchdir, "*.zip");
                if (zippedFiles.Length > 0)
                {
                    for (int i = 0; i < zippedFiles.Length; i++)
                    {
                        string file = zippedFiles[i];
                        if (!string.IsNullOrEmpty(file))
                        {
                            try
                            {
                                using (var fileStream = File.OpenRead(file))
                                {
                                    using (var zipInputStream = new ZipInputStream(fileStream))
                                    {
                                        ZipEntry entry;
                                        while ((entry = zipInputStream.GetNextEntry()) != null)
                                        {
                                            string filename = Path.GetFileName(entry.Name);
                                            if (string.IsNullOrEmpty(filename) || !filename.EndsWith(".dll"))
                                            {
                                                continue;
                                            }

                                            if (plugins)
                                            {
                                                if ((Imports.IsDevPluginsOnly() && !filename.EndsWith("-dev.dll")) || (!Imports.IsDevPluginsOnly() && filename.EndsWith("-dev.dll")))
                                                {
                                                    continue;
                                                }
                                            }
                                            else
                                            {
                                                if ((Imports.IsDevModsOnly() && !filename.EndsWith("-dev.dll")) || (!Imports.IsDevModsOnly() && filename.EndsWith("-dev.dll")))
                                                {
                                                    continue;
                                                }
                                            }

                                            using (var unzippedFileStream = new MemoryStream())
                                            {
                                                int    size   = 0;
                                                byte[] buffer = new byte[4096];
                                                while (true)
                                                {
                                                    size = zipInputStream.Read(buffer, 0, buffer.Length);
                                                    if (size > 0)
                                                    {
                                                        unzippedFileStream.Write(buffer, 0, size);
                                                    }
                                                    else
                                                    {
                                                        break;
                                                    }
                                                }
                                                LoadAssembly(unzippedFileStream.ToArray(), plugins, (file + "/" + filename));
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                MelonModLogger.LogError("Unable to load " + file + ":\n" + e.ToString());
                                MelonModLogger.Log("------------------------------");
                            }
                        }
                    }
                }
            }
        }
Example #27
0
        /// <summary>
        /// 解压功能
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <param name="password">密码</param>
        /// <returns>解压结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            bool           result    = true;
            FileStream     fs        = null;
            ZipInputStream zipStream = null;
            ZipEntry       ent       = null;
            string         fileName;

            if (!File.Exists(fileToUnZip))
            {
                return(false);
            }

            if (!Directory.Exists(zipedFolder))
            {
                Directory.CreateDirectory(zipedFolder);
            }

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip.Trim()));
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }
                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        fileName = fileName.Replace('/', '\\');

                        if (fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }

                        using (fs = File.Create(fileName))
                        {
                            int    size = 2048;
                            byte[] data = new byte[size];
                            while (true)
                            {
                                size = zipStream.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    fs.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return(result);
        }
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <param name="password">密码</param>
        /// <returns>解压结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            string         fileName;
            bool           result    = true;
            ZipEntry       ent       = null;
            FileStream     fs        = null;
            ZipInputStream zipStream = null;

            if (!File.Exists(fileToUnZip))
            {
                return(false);
            }

            if (!Directory.Exists(zipedFolder))
            {
                Directory.CreateDirectory(zipedFolder);
            }

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }

                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        //change by Mr.HopeGi
                        fileName = fileName.Replace('/', '\\');

                        int index = ent.Name.LastIndexOf('/');
                        if (index != -1 || fileName.EndsWith("\\"))
                        {
                            string tmpDir = (index != -1 ? fileName.Substring(0, fileName.LastIndexOf('\\')) : fileName) + "\\";
                            if (!Directory.Exists(tmpDir))
                            {
                                Directory.CreateDirectory(tmpDir);
                            }
                            if (tmpDir == fileName)
                            {
                                continue;
                            }
                        }

                        int size = 2048;
                        fs = File.Create(fileName);
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = zipStream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                fs.Write(data, 0, data.Length);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            return(result);
        }
        /// <summary>
        /// 功能:解压zip格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <param name="err">出错信息</param>
        /// <returns>解压是否成功</returns>
        public bool UnZipFile(string zipFilePath, string unZipDir, out string err)
        {
            err = "";
            if (zipFilePath == string.Empty)
            {
                err = "压缩文件不能为空!";
                return(false);
            }
            if (!File.Exists(zipFilePath))
            {
                err = "压缩文件不存在!";
                return(false);
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
            if (unZipDir == string.Empty)
            {
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            }
            if (!unZipDir.EndsWith("\\"))
            {
                unZipDir += "\\";
            }
            if (!Directory.Exists(unZipDir))
            {
                Directory.CreateDirectory(unZipDir);
            }

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName      = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("\\"))
                        {
                            directoryName += "\\";
                        }
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                            {
                                int    size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }//while
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return(false);
            }
            return(true);
        }//解压结束
Example #30
0
        /// <summary>
        /// 取zip文件中的指定文件
        /// Android *.apk AndroidManifest.xml
        /// iOS *.ipa iTunesMetadata.plist
        /// WP *.* AppManifest.xaml
        /// </summary>
        /// <param name="zipFileName">zip文件</param>
        /// <param name="innerFileName">需要取的文件名</param>
        /// <param name="fuzzySame">模糊比较文件名</param>
        /// <returns></returns>
        public static byte[] ReadInnerFileBytes(string zipFileName, string innerFileName, bool fuzzySame)
        {
            if (!File.Exists(zipFileName))
            {
                return(null);
            }

            innerFileName = innerFileName.ToLower();
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
            {
                ZipEntry entry;//AndroidManifest.xml
                while ((entry = s.GetNextEntry()) != null)
                {
                    string srcName = entry.Name.ToLower();

                    if (entry.Name == innerFileName || fuzzySame && srcName.IndexOf(innerFileName) >= 0)
                    {
                        List <byte> dyns    = null;
                        byte[]      buff    = new byte[10240];
                        bool        isFirst = true;

                        while (true)
                        {
                            int size = s.Read(buff, 0, 10240);
                            if (size > 0)
                            {
                                if (isFirst && size < 10240)
                                {
                                    byte[] rr = new byte[size];
                                    Array.Copy(buff, rr, size);
                                    return(rr);
                                }
                                isFirst = false;
                                if (dyns == null)
                                {
                                    dyns = new List <byte>(10240 * 2);
                                }
                                if (size == 10240)
                                {
                                    dyns.AddRange(buff);
                                }
                                else
                                {
                                    for (int i = 0; i < size; i++)
                                    {
                                        dyns.Add(buff[i]);
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(dyns != null?dyns.ToArray() : null);
                    }
                }
            }
            return(null);
        }
Example #31
0
        public void ExerciseGetNextEntry()
        {
            var compressedData = MakeInMemoryZip(
                true,
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
                new RuntimeInfo(null, true),
                new RuntimeInfo(CompressionMethod.Stored, 2, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true)
                );

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            using (var inStream = new ZipInputStream(ms))
            {
                var buffer = new byte[10];

                ZipEntry entry;
                while ((entry = inStream.GetNextEntry()) != null)
                {
                    // Read a portion of the data, so GetNextEntry has some work to do.
                    inStream.Read(buffer, 0, 10);
                }
            }
        }
Example #32
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="zipBytes">需解压的文件字节数组</param>
        /// <param name="destDir">目的目录路径</param>
        /// <returns></returns>
        public static string UnZip(byte[] zipBytes, string destDir)
        {
            string rootFile = " ";
            //读取压缩文件(zip文件),准备解压缩
            MemoryStream   ms = new MemoryStream(zipBytes);
            ZipInputStream s  = new ZipInputStream(ms);
            ZipEntry       theEntry;
            string         path = destDir;
            //解压出来的文件保存的路径

            string rootDir = " ";

            //根目录下的第一个子文件夹的名称
            while ((theEntry = s.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(Util.FromBase64String(theEntry.Name));
                //得到根目录下的第一级子文件夹的名称
                if (rootDir.IndexOf("\\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                }
                string dir = Path.GetDirectoryName(Util.FromBase64String(theEntry.Name));
                //根目录下的第一级子文件夹的下的文件夹的名称
                string fileName = Path.GetFileName(Util.FromBase64String(theEntry.Name));
                //根目录下的文件名称
                if (dir != " ")
                //创建根目录下的子文件夹,不限制级别
                {
                    if (!Directory.Exists(destDir + "\\" + dir))
                    {
                        path = destDir + "\\" + dir;
                        //在指定的路径创建文件夹
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")
                //根目录下的文件
                {
                    path     = destDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")
                //根目录下的第一级子文件夹下的文件
                {
                    if (dir.IndexOf("\\") > 0)
                    //指定文件保存的路径
                    {
                        path = destDir + "\\" + dir;
                    }
                }

                if (dir == rootDir)
                //判断是不是需要保存在根目录下的文件
                {
                    path = destDir + "\\" + rootDir;
                }

                //以下为解压缩zip文件的基本步骤
                //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                if (fileName != String.Empty)
                {
                    if (theEntry.Size == 0 && string.Equals(theEntry.Comment, "d"))
                    {
                        Directory.CreateDirectory(path + "\\" + fileName);
                    }
                    else
                    {
                        FileStream streamWriter = File.Create(path + "\\" + fileName);

                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                    }
                }
            }
            s.Close();

            return(rootFile);
        }
Example #33
0
        public void MixedEncryptedAndPlain()
        {
            var compressedData = MakeInMemoryZip(true,
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", false),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, false),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true)
                );

            var ms = new MemoryStream(compressedData);
            using (var inStream = new ZipInputStream(ms))
            {
                inStream.Password = "******";

                var extractCount = 0;
                var extractIndex = 0;
                ZipEntry entry;
                var decompressedData = new byte[100];

                while ((entry = inStream.GetNextEntry()) != null)
                {
                    extractCount = decompressedData.Length;
                    extractIndex = 0;
                    while (true)
                    {
                        var numRead = inStream.Read(decompressedData, extractIndex, extractCount);
                        if (numRead <= 0)
                        {
                            break;
                        }
                        extractIndex += numRead;
                        extractCount -= numRead;
                    }
                }
                inStream.Close();
            }
        }
Example #34
0
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                lblStatus.Text           = "Đang cài đặt..";
                progress.Position        = 0;
                progress.Properties.Step = 1;

                ZipInputStream zipIn = new ZipInputStream(new MemoryStream(e.Result));
                ZipEntry       entry;

                int fileCount = 0;
                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    fileCount++;
                }
                progress.Properties.Maximum = fileCount;

                zipIn = new ZipInputStream(new MemoryStream(e.Result));
                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    progress.PerformStep();
                    this.Update();

                    string path = Application.StartupPath + "\\" + (entry.Name.ToLower() != "updater.exe" ? entry.Name : "updaternew.exe");

                    if (entry.IsDirectory)
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        continue;
                    }

                    //File.Delete(AppDir + entry.Name);
                    FileStream streamWriter = File.Create(path);
                    long       size         = entry.Size;
                    byte[]     data         = new byte[size];
                    while (true)
                    {
                        size = zipIn.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, (int)size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();

                    if (entry.Name.ToLower() == "updater.exe")
                    {
                        RepairUpdater();
                    }
                }

                //Luu ver
                string       pathVersion = Application.StartupPath + "\\Version.txt";
                StreamWriter sw          = new StreamWriter(pathVersion);
                sw.WriteLine(NewVersion);
                sw.Close();
                //
                lblStatus.Text    = "Cài đặt hoàn tất";
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("Đã xảy ra lỗi trong quá trình tải xuống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #35
0
        public void ParameterHandling()
        {
            var buffer = new byte[10];
            var emptyBuffer = new byte[0];

            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("Floyd"));
            outStream.Write(buffer, 0, 10);
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);
            var e = inStream.GetNextEntry();

            MustFailRead(inStream, null, 0, 0);
            MustFailRead(inStream, buffer, -1, 1);
            MustFailRead(inStream, buffer, 0, 11);
            MustFailRead(inStream, buffer, 7, 5);
            MustFailRead(inStream, buffer, 0, -1);

            MustFailRead(inStream, emptyBuffer, 0, 1);

            var bytesRead = inStream.Read(buffer, 10, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");

            bytesRead = inStream.Read(emptyBuffer, 0, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");
        }
Example #36
0
        /// <summary>
        /// Decompress
        /// </summary>
        /// <param name="inputStream">Zip inputStream</param>
        /// <param name="outputPath">output folder</param>
        /// <param name="password">password</param>
        /// <param name="unzipCallback">UnzipCallback</param>
        /// <returns></returns>
        public static bool Decompress(Stream inputStream, string outputPath, string password = null, UnzipCallback unzipCallback = null)
        {
            if ((null == inputStream) || string.IsNullOrEmpty(outputPath))
            {
                if (null != unzipCallback)
                {
                    unzipCallback.OnFinished(false);
                }

                return(false);
            }

            // create folder
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            // unzip
            ZipEntry entry = null;

            using (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
                if (!string.IsNullOrEmpty(password))
                {
                    zipInputStream.Password = password;
                }

                while (null != (entry = zipInputStream.GetNextEntry()))
                {
                    if (string.IsNullOrEmpty(entry.Name))
                    {
                        continue;
                    }

                    if ((null != unzipCallback) && !unzipCallback.OnPreUnzip(entry))
                    {
                        continue;                           // filter
                    }
                    string filePathName = Path.Combine(outputPath, entry.Name);

                    // create folder
                    if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(filePathName);
                        continue;
                    }

                    // write to file
                    try {
                        using (FileStream fileStream = File.Create(filePathName)) {
                            byte[] bytes = new byte[1024];
                            while (true)
                            {
                                int count = zipInputStream.Read(bytes, 0, bytes.Length);
                                if (count > 0)
                                {
                                    fileStream.Write(bytes, 0, count);
                                }
                                else
                                {
                                    if (null != unzipCallback)
                                    {
                                        unzipCallback.OnPostUnzip(entry);
                                    }

                                    break;
                                }
                            }
                        }
                    } catch (System.Exception e) {
                        Debug.LogError(e.ToString());

                        if (null != unzipCallback)
                        {
                            unzipCallback.OnFinished(false);
                        }

                        return(false);
                    }
                }
            }

            if (null != unzipCallback)
            {
                unzipCallback.OnFinished(true);
            }

            return(true);
        }
        private static void ExtractFileToStream(ZipInputStream zipStream, Stream destStream)
        {
            int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize;
            byte[] data = new byte[bufferSize];

            int byteCount;
            while ((byteCount = zipStream.Read(data, 0, data.Length)) > 0)
            {
                destStream.Write(data, 0, byteCount);
            }
        }
Example #38
0
    public static string unZipFile(string TargetFile, string fileDir)
    {
        string rootFile = " ";

        try
        {
            //读取压缩文件(zip文件),准备解压缩
            inputStream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
            ZipEntry theEntry;
            string   path = fileDir;
            //解压出来的文件保存的路径

            string rootDir = " ";
            //根目录下的第一个子文件夹的名称
            while ((theEntry = inputStream.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(theEntry.Name);
                //得到根目录下的第一级子文件夹的名称
                if (rootDir.IndexOf("\\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                }
                string dir = Path.GetDirectoryName(theEntry.Name);
                //根目录下的第一级子文件夹的下的文件夹的名称
                string fileName = Path.GetFileName(theEntry.Name);
                //根目录下的文件名称
                if (dir != " ")
                //创建根目录下的子文件夹,不限制级别
                {
                    if (!Directory.Exists(fileDir + "\\" + dir))
                    {
                        path = fileDir + "\\" + dir;
                        //在指定的路径创建文件夹
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")
                //根目录下的文件
                {
                    path     = fileDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")
                //根目录下的第一级子文件夹下的文件
                {
                    if (dir.IndexOf("\\") > 0)
                    //指定文件保存的路径
                    {
                        path = fileDir + "\\" + dir;
                    }
                }

                if (dir == rootDir)
                //判断是不是需要保存在根目录下的文件
                {
                    path = fileDir + "\\" + rootDir;
                }

                //以下为解压缩zip文件的基本步骤
                //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(path + "\\" + fileName);

                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = inputStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }

                    streamWriter.Close();
                }
            }

            inputStream.Close();

            return(rootFile);
        }
        catch (Exception ex)
        {
            // inputStream = null;
            return("1; " + ex.Message);
        }
    }
Example #39
0
    /// <summary>
    /// 解压缩
    /// </summary>
    /// <param name="sourceFile">源文件</param>
    /// <param name="targetPath">目标路经</param>
    public static bool Decompress(string sourceFile, string targetPath, unzipProgressDelegate deleg)
    {
        errorMsg = "";
        long zipFileCount = 0;

        using (ZipFile zip = new ZipFile(sourceFile))
        {
            zipFileCount = zip.Count;
            zip.Close();
        }
        if (!File.Exists(sourceFile))
        {
            throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
        }
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
        {
            int      unZipCount = 0;
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                try
                {
                    string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
                    string fileName     = directorName + "/" + Path.GetFileName(theEntry.Name);
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    // 创建目录
                    if (Directory.Exists(directorName) == false && directorName.Length > 0)
                    {
                        Directory.CreateDirectory(directorName);
                    }
                    if (fileName != string.Empty)
                    {
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int    size = 4096;
                            byte[] data = new byte[4 * 1024];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                                //deleg((float)((double)s.Position / s.Length));
                            }
                            streamWriter.Close();
                            unZipCount++;
                        }
                    }
                    if (deleg != null)
                    {
                        deleg((float)((float)unZipCount / (float)zipFileCount));
                    }
                }
                catch (Exception ex)
                {
                    errorMsg = ex.Message;
                    return(false);
                }
            }
        }
        return(true);
    }
Example #40
0
        /// <summary>
        /// 解压缩一个 zip 文件。
        /// </summary>
        /// <param name="zipedFile">The ziped file.</param>
        /// <param name="strDirectory">The STR directory.</param>
        /// <param name="password">zip 文件的密码。</param>
        /// <param name="overWrite">是否覆盖已存在的文件。</param>
        public bool UnZip(string zipedFile, string strDirectory, string password, bool overWrite)
        {
            if (strDirectory == "")
            {
                strDirectory = Directory.GetCurrentDirectory();
            }
            if (!strDirectory.EndsWith("\\"))
            {
                strDirectory = strDirectory + "\\";
            }

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
                {
                    s.Password = password;
                    ZipEntry theEntry;

                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = "";
                        string pathToZip     = "";
                        pathToZip = theEntry.Name;

                        if (pathToZip != "")
                        {
                            directoryName = Path.GetDirectoryName(pathToZip) + "\\";
                        }

                        string fileName = Path.GetFileName(pathToZip);

                        Directory.CreateDirectory(strDirectory + directoryName);

                        if (fileName != "")
                        {
                            if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
                            {
                                using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
                                {
                                    int    size = 2048;
                                    byte[] data = new byte[2048];
                                    while (true)
                                    {
                                        size = s.Read(data, 0, data.Length);

                                        if (size > 0)
                                        {
                                            streamWriter.Write(data, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                    streamWriter.Close();
                                }
                            }
                        }
                    }
                    s.Close();
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }