Example #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException("fileInfo");
            }

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);
            }

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {
                using (var zip = new ZipInputStream(fileInfo.OpenRead())) {
                    ZipEntry entry;
                    while ((entry = zip.GetNextEntry()) != null)
                    {
                        if (entry.Name == ArtifactProvider.ManifestEntry)
                        {
                            Manifest = (Properties)Properties.Deserialize(new UnclosableStream(zip));
                            zip.CloseEntry();
                            break;
                        }
                        zip.CloseEntry();
                    }

                    zip.Close();
                }
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ModelInfo"/> class.
        /// </summary>
        /// <param name="fileInfo">The model file info.</param>
        /// <exception cref="System.ArgumentNullException">fileInfo</exception>
        /// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
        /// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
        public ModelInfo(FileInfo fileInfo)
        {
            if (fileInfo == null)
            {
                throw new ArgumentNullException(nameof(fileInfo));
            }

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);
            }

            File = fileInfo;
            Name = Path.GetFileNameWithoutExtension(fileInfo.Name);

            try {
                #if ZIPLIB
                using (var zip = new ZipInputStream(fileInfo.OpenRead())) {
                    ZipEntry entry;
                    while ((entry = zip.GetNextEntry()) != null)
                    {
                        if (entry.Name == ArtifactProvider.ManifestEntry)
                        {
                            Manifest = (Properties)Properties.Deserialize(new UnclosableStream(zip));
                            zip.CloseEntry();
                            break;
                        }
                        zip.CloseEntry();
                    }

                    zip.Flush();
                }
                #else
                using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
                    foreach (var entry in zip.Entries)
                    {
                        if (entry.Name != ArtifactProvider.ManifestEntry)
                        {
                            continue;
                        }

                        using (var stream = entry.Open()) {
                            Manifest = (Properties)Properties.Deserialize(stream);
                            break;
                        }
                    }
                }
                #endif
            } catch (Exception ex) {
                throw new InvalidFormatException("Unable to load the specified model file.", ex);
            }
        }
Example #3
0
        public void Check()
        {
            string entryName = "";

            using (ZipInputStream zipStream = new ZipInputStream(input))
            {
                try
                {
                    int      entryIndex = 0;
                    ZipEntry entry      = null;
                    int      jobIndex   = nextJob++;
                    while ((entry = zipStream.GetNextEntry()) != null)
                    {
                        if (entry.IsDirectory)
                        {
                            continue;
                        }
                        if (entryIndex++ != jobIndex)
                        {
                            zipStream.CloseEntry();
                            continue;
                        }
                        entryName = entry.Name;
                        int    dotIndex       = entryName.IndexOf('.');
                        string entryCrcString = (dotIndex == -1) ? entryName : entryName.Substring(0, dotIndex);
                        long   entryCrc       = Convert.ToInt64(entryCrcString, 16);
                        try
                        {
                            if (entryCrc != DecompressAndCalculateCrc(zipStream) && !sanityCheck)
                            {
                                throw new Exception("CRC mismatch");
                            }
                        }
                        catch (IOException iox)
                        {
                            if (!sanityCheck)
                            {
                                throw new Exception("Decompression failed", iox);
                            }
                        }
                        zipStream.CloseEntry();
                        entryName = "";
                        jobIndex  = nextJob++;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Example #4
0
        public void UnZip()
        {
            try
            {
                var fileInputStream = new System.IO.FileStream(_zipFile, System.IO.FileMode.Open);
                var zipInputStream  = new ZipInputStream(fileInputStream);

                ZipEntry zipEntry = null;

                while ((zipEntry = zipInputStream.NextEntry) != null)
                {
                    if (zipEntry.IsDirectory)
                    {
                        DirChecker(zipEntry.Name);
                    }
                    else
                    {
                        var fileOutputStream = new FileOutputStream(_location + zipEntry.Name);

                        for (int i = zipInputStream.Read(); i != -1; i = zipInputStream.Read())
                        {
                            fileOutputStream.Write(i);
                        }

                        zipInputStream.CloseEntry();
                        fileOutputStream.Close();
                    }
                }
                zipInputStream.Close();
            }
            catch (Exception ex)
            {
            }
        }
Example #5
0
        /// <summary>
        /// 读取zip中指定路径的文件;
        ///
        /// 如:
        /// zipPath="E:/tmp/1.apk"
        /// entryName ="assets/ltpay_config.txt"
        /// </summary>
        public static string ReadFile(String zipPath, String entryName, Encoding encode = null, String Password = null)
        {
            string data = "";

            if (encode == null)
            {
                encode = Encoding.UTF8;
            }
            ZipInputStream zipStream = null;

            zipStream = new ZipInputStream(File.OpenRead(zipPath));
            if (Password != null && !Password.Equals(""))
            {
                zipStream.Password = Password;
            }

            ZipEntry entry = null;

            while ((entry = zipStream.GetNextEntry()) != null && data.Equals(""))
            {
                if (entry.Name.Equals(entryName))
                {
                    long   len  = zipStream.Length;
                    byte[] buff = new byte[len];

                    zipStream.Read(buff, 0, Convert.ToInt32(len));
                    data = encode.GetString(buff);
                }
                zipStream.CloseEntry();
            }
            zipStream.Close();

            return(data);
        }
Example #6
0
        /// <summary>
        /// Deserializes the specified input stream.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <exception cref="System.ArgumentNullException">inputStream</exception>
        /// <exception cref="InvalidFormatException">Unable to find the manifest file.</exception>
        protected void Deserialize(Stream inputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream");
            }

            var isSearchingForManifest = true;

            var lazyStack = new Stack <LazyArtifact>();

            using (var zip = new ZipInputStream(new UnclosableStream(inputStream))) {
                ZipEntry entry;
                while ((entry = zip.GetNextEntry()) != null)
                {
                    if (entry.Name == ManifestEntry)
                    {
                        isSearchingForManifest = false;

                        artifactMap[ManifestEntry] = Properties.Deserialize(new UnclosableStream(zip));

                        zip.CloseEntry();

                        ManifestDeserialized();

                        CreateArtifactSerializers();

                        FinishLoadingArtifacts(lazyStack, zip);

                        break;
                    }

                    lazyStack.Push(new LazyArtifact(entry, zip));

                    zip.CloseEntry();
                }
            }

            if (isSearchingForManifest)
            {
                lazyStack.Clear();
                throw new InvalidFormatException("Unable to find the manifest file.");
            }
        }
Example #7
0
        /**
         * 解压文件
         *
         * @param filePath 压缩文件路径
         */
        public static void unzip(string filePath)
        {
            //isSuccess = false;
            File source = new File(filePath);

            if (source.Exists())
            {
                ZipInputStream       zis = null;
                BufferedOutputStream bos = null;
                try
                {
                    zis = new ZipInputStream(new System.IO.FileStream(source.Path, System.IO.FileMode.Append));
                    ZipEntry entry = null;
                    while ((entry = zis.NextEntry) != null &&
                           !entry.IsDirectory)
                    {
                        File target = new File(source.Parent, entry.Name);
                        if (!target.ParentFile.Exists())
                        {
                            // 创建文件父目录
                            target.ParentFile.Mkdirs();
                        }
                        // 写入文件
                        bos = new BufferedOutputStream(new System.IO.FileStream(target.Path, System.IO.FileMode.Append));
                        int    read   = 0;
                        byte[] buffer = new byte[1024 * 10];
                        while ((read = zis.Read(buffer, 0, buffer.Length)) != -1)
                        {
                            bos.Write(buffer, 0, read);
                        }
                        bos.Flush();
                    }
                    zis.CloseEntry();
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
                finally
                {
                    zis.Close();
                    bos.Close();
                    // isSuccess = true;
                }
            }
        }
Example #8
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Unzip a byte array and return unpacked data
 /// </summary>
 /// <param name="data">Byte array containing data to be unzipped</param>
 /// <returns>unpacked data</returns>
 /// ------------------------------------------------------------------------------------
 public static byte[] UnpackData(byte[] data)
 {
     if (data == null)
     {
         return(null);
     }
     try
     {
         using (MemoryStream memStream = new MemoryStream(data))
         {
             using (var zipStream = new ZipInputStream(memStream))
             {
                 zipStream.GetNextEntry();
                 using (var streamWriter = new MemoryStream())
                 {
                     int    size = 2048;
                     byte[] dat  = new byte[2048];
                     while (true)
                     {
                         size = zipStream.Read(dat, 0, dat.Length);
                         if (size > 0)
                         {
                             streamWriter.Write(dat, 0, size);
                         }
                         else
                         {
                             break;
                         }
                     }
                     streamWriter.Close();
                     zipStream.CloseEntry();
                     zipStream.Close();
                     memStream.Close();
                     return(streamWriter.ToArray());
                 }
             }
         }
     }
     catch (Exception e)
     {
         System.Console.Error.WriteLine("Got exception: {0} while unpacking data.",
                                        e.Message);
         throw;
     }
 }
        public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
        {
            try
            {
                _location = destinationDirectoryName;
                if (!_location.EndsWith("/"))
                {
                    _location += "/";
                }
                var      fileInputStream = new FileStream(sourceArchiveFileName, FileMode.Open);
                var      zipInputStream  = new ZipInputStream(fileInputStream);
                ZipEntry zipEntry        = null;

                while ((zipEntry = zipInputStream.NextEntry) != null)
                {
                    xLog.Debug("UnZipping : " + zipEntry.Name);

                    if (zipEntry.IsDirectory)
                    {
                        DirChecker(zipEntry.Name);
                    }
                    else
                    {
                        var fileOutputStream = new Java.IO.FileOutputStream(_location + zipEntry.Name);

                        for (int i = zipInputStream.Read(); i != -1; i = zipInputStream.Read())
                        {
                            fileOutputStream.Write(i);
                        }

                        zipInputStream.CloseEntry();
                        fileOutputStream.Close();
                    }
                }
                zipInputStream.Close();
            }
            catch (Exception ex)
            {
                xLog.Error(ex);
            }
        }
Example #10
0
        public void UnZip()
        {
            byte[] buffer          = new byte[65536];
            var    fileInputStream = System.IO.File.OpenRead(_zipFile);

            var      zipInputStream = new ZipInputStream(fileInputStream);
            ZipEntry zipEntry       = null;
            int      j        = 0;
            int      bestRead = 0;

            while ((zipEntry = zipInputStream.NextEntry) != null)
            {
                OnContinue?.Invoke(zipEntry.Name + ", " + bestRead);
                if (zipEntry.IsDirectory)
                {
                    DirChecker(zipEntry.Name);
                }
                else
                {
                    if (System.IO.File.Exists(_location + zipEntry.Name))
                    {
                        System.IO.File.Delete(_location + zipEntry.Name);
                    }
                    var foS = new FileOutputStream(_location + zipEntry.Name, true);
                    int read;
                    while ((read = zipInputStream.Read(buffer)) > 0)
                    {
                        if (read > bestRead)
                        {
                            bestRead = read;
                        }
                        foS.Write(buffer, 0, read);
                    }
                    foS.Close();
                    zipInputStream.CloseEntry();
                }
            }
            zipInputStream.Close();
            fileInputStream.Close();
        }
Example #11
0
        /// <summary>
        /// Funkcja ogolnie nie uzyteczna. Pokazuje jednak jak uzyc
        /// biblioteki.
        /// </summary>
        /// <param name="path">Scierzka do skompresowanego pliku.</param>
        /// <returns>Pierwszy wczytany plik.</returns>
        public static string Read(string path)
        {
            ZipInputStream zipStream = null;

            try
            {
                zipStream = new ZipInputStream(File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read));
                ZipEntry entry = null;
                while ((entry = zipStream.GetNextEntry()) != null)
                {
                    if (entry.IsFile && zipStream.CanDecompressEntry)
                    {
                        byte[] array = new byte[entry.CompressedSize];
                        int    size  = zipStream.Read(array, 0, (int)entry.CompressedSize);
                        if (size > 0)
                        {
                            return(new ASCIIEncoding().GetString(array));
                        }
                        else
                        {
                            return("Nie udalo sie odczytac pliku !");
                        }
                    }
                    zipStream.CloseEntry();
                }
                return(String.Empty);
            }
            catch (Exception)
            {
                return(String.Empty);
            }
            finally
            {
                if (zipStream != null)
                {
                    zipStream.Close();
                }
            }
        }
Example #12
0
        public static Dictionary <String, byte[]> ReadParts(byte[] data)
        {
            Dictionary <String, byte[]> binaries = new Dictionary <String, byte[]>();

            using (MemoryStream input = new MemoryStream(data)) {
                using (ZipInputStream zip = new ZipInputStream(input)) {
                    zip.IsStreamOwner = false;
                    for (;;)
                    {
                        ZipEntry entry = zip.GetNextEntry();
                        if (entry == null)
                        {
                            break;
                        }
                        data = IOUtils.ReadStreamFully(zip);
                        binaries[entry.Name] = data;
                        zip.CloseEntry();
                    }
                    return(binaries);
                }
            }
        }
        public static byte[] Unpack(byte[] compressedData)
        {
            var memZipStream = new MemoryStream(compressedData);
            var memStream    = new MemoryStream();
            var zipInput     = new ZipInputStream(memZipStream);

            zipInput.GetNextEntry();

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

            do
            {
                size = zipInput.Read(data, 0, data.Length);
                memStream.Write(data, 0, size);
            } while (size > 0);

            var streamdata = memStream.ToArray();

            zipInput.CloseEntry();
            zipInput.Close();
            memStream.Close();
            return(streamdata);
        }
Example #14
0
        public static void SetupShell(string target)
        {
            // Unzip
            var root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

            if (!Directory.Exists(root + "/" + target))
            {
                Log.Debug("Ruly", "extracting default Shell...");
                using (var s = Application.Context.Assets.Open("Shell/" + target + ".zip"))
                    using (var z = new ZipInputStream(s))
                    {
                        ZipEntry ze;
                        byte[]   buf = new byte[1024];
                        while ((ze = z.NextEntry) != null)
                        {
                            if (!ze.IsDirectory)
                            {
                                string name = root + "/" + ze.Name;
                                Util.EnsureDirectory(System.IO.Path.GetDirectoryName(name));
                                using (var ws = File.OpenWrite(name))
                                {
                                    var i = 0;
                                    while (i < ze.Size)
                                    {
                                        int num = z.Read(buf, 0, 1024);
                                        ws.Write(buf, 0, num);
                                        i += num;
                                    }
                                    z.CloseEntry();
                                    Log.Debug("Ruly", "Extract File " + ze.Name);
                                }
                            }
                        }
                    }
            }
        }
Example #15
0
        /// <summary>
        /// Finish loading the artifacts now that it knows all serializers.
        /// </summary>
        private void FinishLoadingArtifacts(Stack <LazyArtifact> lazyStack, ZipInputStream zip)
        {
            // process the lazy artifacts
            while (lazyStack.Count > 0)
            {
                using (var lazy = lazyStack.Pop()) {
                    LoadArtifact(lazy.Name, lazy.Data);
                }
            }

            // process the "normal" artifacts
            ZipEntry entry;

            while ((entry = zip.GetNextEntry()) != null)
            {
                if (entry.Name != ManifestEntry)
                {
                    LoadArtifact(entry.Name, zip);
                }
                zip.CloseEntry();
            }

            FinishedLoadingArtifacts = true;
        }
Example #16
0
        /// <summary>
        /// Deserializes the specified input stream.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <exception cref="System.ArgumentNullException">inputStream</exception>
        /// <exception cref="InvalidFormatException">Unable to find the manifest file.</exception>
        protected void Deserialize(Stream inputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }

            var isSearchingForManifest = true;

            try {
                #if ZIPLIB
                var lazyStack = new Stack <LazyArtifact>();
                using (var zip = new ZipInputStream(new UnclosableStream(inputStream))) {
                    ZipEntry entry;
                    while ((entry = zip.GetNextEntry()) != null)
                    {
                        if (entry.Name == ManifestEntry)
                        {
                            isSearchingForManifest = false;

                            artifactMap[ManifestEntry] = Properties.Deserialize(new UnclosableStream(zip));

                            zip.CloseEntry();

                            ManifestDeserialized();

                            CreateArtifactSerializers();

                            FinishLoadingArtifacts(lazyStack, zip);

                            break;
                        }

                        lazyStack.Push(new LazyArtifact(entry, zip));

                        zip.CloseEntry();
                    }
                }
                #else
                using (var zip = new ZipArchive(inputStream, ZipArchiveMode.Read, true)) {
                    foreach (var entry in zip.Entries)
                    {
                        if (entry.Name != ManifestEntry)
                        {
                            continue;
                        }

                        isSearchingForManifest = false;

                        using (var stream = entry.Open())
                            artifactMap[ManifestEntry] = Properties.Deserialize(stream);

                        ManifestDeserialized();

                        CreateArtifactSerializers();

                        FinishLoadingArtifacts(zip);


                        break;
                    }
                }
                #endif
            } catch (Exception ex) {
                throw new InvalidOperationException("An error had occurred during the deserialization of the model file.", ex);
            }

            if (!isSearchingForManifest)
            {
                return;
            }

            throw new InvalidFormatException("Unable to find the manifest file.");
        }
Example #17
0
        public static bool UnpackZipArchive(string zipPath, File pathToExtract)
        {
            var            buffer      = 2048;
            FileStream     inputStream = null;
            ZipInputStream zis         = null;
            ZipFile        zipFile     = null;
            int            k           = 0;

            try
            {
                zipFile     = new ZipFile(zipPath);
                inputStream = new FileStream(zipPath, FileMode.Open);
                zis         = new ZipInputStream(new BufferedStream(inputStream));
                ZipEntry ze;
                var      data = new byte[buffer];

                while ((ze = zis.NextEntry) != null)
                {
                    k++;
                    var filename = ze.Name;

                    if (ze.IsDirectory)
                    {
                        var fmd = new File(pathToExtract, filename);
                        fmd.Mkdirs();
                        continue;
                    }

                    var current = new File(pathToExtract, filename);

                    Log.Debug(nameof(UnpackZipArchive), current.AbsolutePath);

                    FileOutputStream fout = null;
                    try
                    {
                        fout = new FileOutputStream(current);
                        int count;
                        while ((count = zis.Read(data)) != -1)
                        {
                            fout.Write(data, 0, count);
                        }
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                    finally
                    {
                        fout?.Close();
                        zis.CloseEntry();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(nameof(UnpackZipArchive), e.Message);
                return(false);
            }
            finally
            {
                inputStream?.Close();
                zis?.Close();
                zipFile?.Close();
            }

            return(k > 0);
        }
Example #18
0
        /// <summary>
        /// 解压文件 到指定的路径,可通过targeFileNames指定解压特定的文件
        /// </summary>
        public static bool unzip(String zipPath, String targetPath = null, String Password = null, String[] targeFileNames = null)
        {
            if (File.Exists(zipPath))
            {
                if (targetPath == null || targetPath.Equals(""))
                {
                    targetPath = FileTools.getPathNoExt(zipPath);
                }
                Console.WriteLine("解压文件:" + zipPath);
                Console.WriteLine("解压至目录:" + targetPath);

                try
                {
                    ZipInputStream zipStream = null;
                    FileStream     bos       = null;

                    zipStream = new ZipInputStream(File.OpenRead(zipPath));
                    if (Password != null && !Password.Equals(""))
                    {
                        zipStream.Password = Password;
                    }

                    ZipEntry entry = null;
                    while ((entry = zipStream.GetNextEntry()) != null)
                    {
                        if (targeFileNames != null && targeFileNames.Length > 0)                // 若指定了目标解压文件
                        {
                            if (!ContainsIgnoreName(entry.Name, targeFileNames))
                            {
                                continue;                                                       // 跳过非指定的文件
                            }
                        }

                        String target = targetPath + "\\" + entry.Name;
                        if (entry.IsDirectory)
                        {
                            FileTools.mkdirs(target);                    // 创建目标路径
                        }
                        if (entry.IsFile)
                        {
                            FileTools.mkdirs(FileTools.getParent(target));

                            bos = File.Create(target);
                            Console.WriteLine("解压生成文件:" + target);

                            int    read   = 0;
                            byte[] buffer = new byte[10240];
                            while ((read = zipStream.Read(buffer, 0, 10240)) > 0)
                            {
                                bos.Write(buffer, 0, read);
                            }
                            bos.Flush();
                            bos.Close();
                        }
                    }
                    zipStream.CloseEntry();

                    Console.WriteLine("解压完成!");
                    return(true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());;
                }
            }
            return(false);
        }
Example #19
0
 private void SelectDirectory_ValidateStep(object sender, CancelEventArgs e)
 {
     //System.Threading.Thread t=null;
     if (this.treedir.SelectedNode != null && this.treedir.SelectedNode.Tag is DirectoryInfo)
     {
         DirectoryInfo dir = (DirectoryInfo)this.treedir.SelectedNode.Tag;
         lastpath = dir.FullName;
         this.Wizard.Data[DIRECTORY_PATH] = lastpath;
         rep     = this.Wizard.Data[Search.REPOSITORY_ID].ToString();
         version = (VersionInfo)this.Wizard.Data[SelectVersionToOpen.VERSION];
         IOfficeApplication app = OfficeApplication.OfficeApplicationProxy;
         this.Wizard.SetProgressBarInit(5, 1, "Descargando contenido...");
         fileName = app.openContent(rep, version);
         this.Wizard.SetProgressBarInit(5, 2, "Validando contenido...");
         String pathFile = dir.FullName + "/" + fileName;
         pathFile    = pathFile.Replace('/', '\\');
         contentfile = new FileInfo(pathFile);
         if (contentfile.Exists)
         {
             DialogResult res = MessageBox.Show(this, "Existe un archivo con el nombre " + fileName + "\r\n¿Desea sobre escribir el archivo?", this.Wizard.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
             if (res == DialogResult.Yes)
             {
                 try
                 {
                     contentfile.Delete();
                 }
                 catch (Exception ue)
                 {
                     MessageBox.Show(ue.Message, this.Wizard.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                     return;
                 }
             }
             else
             {
                 return;
             }
         }
         String   guid    = Guid.NewGuid().ToString().Replace('-', '_');
         FileInfo zipFile = new FileInfo(dir.FullName + "/" + guid + ".zip");
         try
         {
             foreach (Part part in OfficeApplication.OfficeApplicationProxy.ResponseParts)
             {
                 FileStream fout = zipFile.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                 fout.Write(part.getContent(), 0, part.getContent().Length);
                 fout.Close();
             }
             using (ZipInputStream s = new ZipInputStream(zipFile.OpenRead()))
             {
                 ZipEntry entry;
                 // extract the file or directory entry
                 while ((entry = s.GetNextEntry()) != null)
                 {
                     if (entry.IsDirectory)
                     {
                         ExtractDirectory(s, entry.Name, entry.DateTime, zipFile.Directory);
                     }
                     else
                     {
                         ExtractFile(s, entry.Name, entry.DateTime, entry.Size, zipFile.Directory);
                     }
                     s.CloseEntry();
                 }
                 s.Close();
             }
             this.Wizard.SetProgressBarInit(5, 3, "Abriendo contenido...");
             //t = new System.Threading.Thread(new System.Threading.ThreadStart(open));
             this.Wizard.Visible = false;
             this.Wizard.Close();
         }
         catch (Exception ue)
         {
             MessageBox.Show(this, "El contenido tiene una falla\r\nDetalle: " + ue.Message, this.Wizard.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
         finally
         {
             zipFile.Delete();
         }
     }
     else
     {
         MessageBox.Show(this, "¡Debe indicar un directorio!", this.Wizard.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Example #20
0
            void unzip()
            {
                System.IO.FileStream fin = null;
                ZipInputStream       zin = null;

                try
                {
                    fin = new System.IO.FileStream(_zipFile, System.IO.FileMode.Open);
                    zin = new ZipInputStream(fin);
                    ZipEntry ze = null;

                    byte[] buf = new byte[1024 * 4];

                    while ((ze = zin.NextEntry) != null)
                    {
                        if (ze.IsDirectory)
                        {
                            _dirChecker(ze.Name);
                        }
                        else
                        {
                            FileOutputStream fout = null;
                            try
                            {
                                fout = new FileOutputStream(Path.Combine(_location, ze.Name));

                                while (true)
                                {
                                    int count = zin.Read(buf);
                                    if (count < 0)
                                    {
                                        break;
                                    }

                                    fout.Write(buf, 0, count);
                                }

                                //for (int c = zin.Read(); c != -1; c = zin.Read())
                                //    fout.Write(c);
                            }
                            finally
                            {
                                if (fout != null)
                                {
                                    fout.Close();
                                }
                            }
                        }

                        zin.CloseEntry();
                    }
                }
                finally
                {
                    if (zin != null)
                    {
                        zin.Close();              //top first
                    }
                    if (fin != null)
                    {
                        fin.Close();
                    }
                }
            }
Example #21
0
        }         // proc UpdateMetaData

        protected override void ProcessRecord()
        {
            var notify     = new CmdletNotify(this);
            var totalBytes = 0L;

            // Lese den Index ein
            var index = new FileIndex();

            index.ReadIndex(notify, Path.Combine(Source, "index.txt.gz"));

            // Suche alle aktiven Archive
            var archives = new Dictionary <string, List <FileIndexItem> >(StringComparer.OrdinalIgnoreCase);

            using (var bar = notify.CreateStatus("Wiederherstellen eines Verzeichnisses", $"Wiederherstellen von {Source}..."))
            {
                var filter = new FileFilterRules(Filter);                 // Erzeuge Filter und entferne alle Dateien aus dem Index die dem nicht entsprechen
                if (filter.IsEmpty)
                {
                    foreach (var c in index)
                    {
                        AddArchive(archives, c, ref totalBytes);
                    }
                }
                else
                {
                    var remove = new List <FileIndexItem>();
                    foreach (var c in index)
                    {
                        if (filter.IsFiltered(c.RelativePath))
                        {
                            AddArchive(archives, c, ref totalBytes);
                        }
                        else
                        {
                            remove.Add(c);
                        }
                    }

                    foreach (var c in remove)
                    {
                        index.RemoveEntry(c);
                    }
                }

                // Entpacke die Archvie
                bar.StartRemaining();
                bar.Maximum = totalBytes;

                foreach (var c in archives)
                {
                    if (Stuff.IsGZipFile(c.Key) || Stuff.IsNoPackFile(c.Key))                     // GZip-Datei
                    {
                        using (var src = Stuff.OpenRead(new FileInfo(Path.Combine(Source, c.Key)), notify, CompressMode.Auto))
                        {
                            var srcFile = c.Value[0];
                            var dstFile = new FileInfo(Path.Combine(Target, srcFile.RelativePath));
                            using (var dst = Override ? Stuff.OpenWrite(dstFile, notify) : Stuff.OpenCreate(dstFile, notify))
                            {
                                dst.SetLength(srcFile.Length);
                                Stuff.CopyRawBytes(bar, srcFile.RelativePath, srcFile.Length, src, dst);
                            }

                            // Aktualisiere die Attribute
                            UpdateMetaData(notify, srcFile, dstFile);
                        }
                    }
                    else                     // zip-Datei
                    {
                        using (var zipStream = Stuff.OpenRead(new FileInfo(Path.Combine(Source, c.Key)), notify, CompressMode.Stored))
                            using (var zip = new ZipInputStream(zipStream))
                            {
                                var srcEntry = zip.GetNextEntry();
                                while (srcEntry != null)
                                {
                                    // Suche den passenden Index
                                    var srcIndex = c.Value.Find(c2 => String.Compare(srcEntry.Name, ZipEntry.CleanName(c2.RelativePath), StringComparison.OrdinalIgnoreCase) == 0);
                                    if (srcIndex != null)
                                    {
                                        var dstFile = new FileInfo(Path.Combine(Target, srcIndex.RelativePath));
                                        using (var dst = Override ? Stuff.OpenWrite(dstFile, notify) : Stuff.OpenCreate(dstFile, notify))
                                        {
                                            dst.SetLength(srcIndex.Length);
                                            Stuff.CopyRawBytes(bar, srcIndex.RelativePath, srcIndex.Length, zip, dst);
                                        }

                                        // Aktualisiere die Attribute
                                        UpdateMetaData(notify, srcIndex, dstFile);
                                    }
                                    else
                                    {
                                        zip.CloseEntry();
                                    }

                                    // Schließe den Eintrag ab
                                    srcEntry = zip.GetNextEntry();
                                }
                            }
                    }
                }
            }
        }         // proc ProcessRecord
Example #22
0
        public static void GetFirmwareDetails(FirmFinder form, string url, ref RomDetailsClass romDetails, int DetailsKind)
        {
            string VersionID = GetVersionID(url);

            if (DetailsKind == 0 || DetailsKind == 2)
            {
                romDetails.ApprovedForInstall = ApprovedForInstallation(VersionID);
                if (romDetails.ApprovedForInstall)
                {
                    romDetails.FirmName = StaticFirmName;
                }
            }


            if (DetailsKind == 0)
            {
                return;
            }

            Progress progress   = null;
            bool     Finished   = false;
            Thread   thisthread = Thread.CurrentThread;

            form.Invoke(new Action(() =>
            {
                progress              = new Progress("Getting Package URL");
                progress.FormClosing += delegate
                {
                    if (!Finished)
                    {
                        thisthread.Abort();
                    }
                };
                progress.Show(form);
            }));

            SetProgress(form, progress, 5);
            string Package = GetPackageURL(url);

            SetProgress(form, progress, 30, "Initial Request To ZIP");
            HTTPStream httpstream = new HTTPStream(Package);

            ZipInputStream stream = new ZipInputStream(httpstream);

            SetProgress(form, progress, 40, "Exploring ZIP File...");
            int count = 0;

            while (true)
            {
                ZipEntry entry = stream.GetNextEntry();
                if (entry != null)
                {
                    count += 2;
                    if (count > 60)
                    {
                        count = 30;
                    }
                    SetProgress(form, progress, 40 + count, entry.Name);
                    if (entry.Name.Contains("SOFTWARE_VER_LIST.mbn"))
                    {
                        int    read    = 4096;
                        byte[] buffer  = new byte[read];
                        string content = "";
                        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            content += Encoding.UTF8.GetString(buffer, 0, read);
                        }
                        romDetails.SupportedVersions = content.Split('\n');
                        break;
                    }
                    else
                    {
                        stream.CloseEntry();
                    }
                }
                else
                {
                    MessageBox.Show("Seems like I couldn't load the data :(", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                }
            }
            Finished = true;
            progress.Close();
        }
Example #23
0
        // 发现放到外面也没有什么性能提升 , 反而使用 ICSharpCode.SharpZipLib 还产生了内存泄漏
        private IEnumerator InitAssetBundles()
        {
            // 判断是否需要更新
            controller.UpdateInfo("检查资源文件中......");
            string txt = null;

            using (WWW www = new WWW(Application.streamingAssetsPath + "/AssetBundle.txt")) {
                yield return(www);

                using (StreamReader sr = new StreamReader(new MemoryStream(www.bytes))) {
                    txt = sr.ReadLine();
                }
            }
            // 先检查标志文件是否存在
            if (File.Exists(Application.persistentDataPath + "/AssetBundle.txt"))
            {
                using (StreamReader sr = File.OpenText(Application.persistentDataPath + "/AssetBundle.txt")) {
                    string str = sr.ReadLine();
                    if (str != txt)
                    {
                        File.Delete(Application.persistentDataPath + "/AssetBundle.txt");
                        using (StreamWriter sw = File.CreateText(Application.persistentDataPath + "/AssetBundle.txt")) {
                            sw.Write(txt.ToCharArray());
                            sw.Flush();
                        }
                    }
                    else
                    {
                        init = true;
                        LoadManifest();
                        Destroy(assetBundleInitCanvas);
                        yield break;
                    }
                }
            }
            else
            {
                // 不存在则创建标志文件
                using (StreamWriter sw = File.CreateText(Application.persistentDataPath + "/AssetBundle.txt")) {
                    sw.Write(txt.ToCharArray());
                    sw.Flush();
                }
            }

            controller.UpdateInfo("正在加载资源压缩包......");
            using (MemoryStream ms = new MemoryStream()) {
                using (WWW www = new WWW(Application.streamingAssetsPath + "/AssetBundles.zip")) {
                    yield return(www);

                    ms.Write(www.bytes, 0, www.bytesDownloaded);
                    ms.Seek(0L, SeekOrigin.Begin);
                    controller.InitSlider(www.bytesDownloaded);
                }
                controller.UpdateInfo("资源解压中......");
                using (ZipInputStream zipInput = new ZipInputStream(ms)) {
                    ZipEntry zipEntry = null;
                    string   fileName = "";
                    byte[]   datas    = new byte[4 * 1024];
                    while ((zipEntry = zipInput.GetNextEntry()) != null)
                    {
                        if (zipEntry.Name.EndsWith(".meta") || zipEntry.Name.EndsWith(".manifest"))
                        {
                            zipInput.CloseEntry();
                            continue;
                        }
                        fileName = Application.persistentDataPath + "/" + zipEntry.Name;
                        if (zipEntry.IsFile)
                        {
                            if (File.Exists(fileName))
                            {
                                File.Delete(fileName);          // 如果存在则先删除 , 然后创建一个新的
                            }
                            using (FileStream fs = File.Create(fileName)) {
                                int count = 0;
                                while ((count = zipInput.Read(datas, 0, datas.Length)) > 0)
                                {
                                    fs.Write(datas, 0, count);
                                }
                                fs.Flush();
                            }
                            controller.UpdateProgress((int)zipEntry.Size);      // 更新进度条
                        }
                        else
                        {
                            if (!Directory.Exists(fileName))
                            {
                                Directory.CreateDirectory(fileName);
                            }
                        }
                        zipInput.CloseEntry();
                        yield return(null);
                    }
                }
            }
            LoadManifest();
            init = true;
            Destroy(assetBundleInitCanvas);
        }