Example #1
1
        public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder)
        {
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
            try {
                FileStream fs = File.OpenRead (archiveFilenameIn);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile (fs);
                if (!String.IsNullOrEmpty (password)) {
                    zf.Password = password;		// AES encrypted entries are handled automatically
                }
                foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf) {
                    if (!zipEntry.IsFile) {
                        continue;			// Ignore directories
                    }
                    String entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    byte[] buffer = new byte[4096];		// 4K is optimum
                    Stream zipStream = zf.GetInputStream (zipEntry);

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine (outFolder, entryFileName);
                    string directoryName = Path.GetDirectoryName (fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory (directoryName);

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create (fullZipToPath)) {
                        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy (zipStream, streamWriter, buffer);
                    }
                }
            } finally {
                if (zf != null) {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close (); // Ensure we release resources
                }
            }
        }
        public static void ExtractFileAndSave(string APKFilePath, string fileResourceLocation, string FilePathToSave, int index)
        {
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(APKFilePath)))
            {
                using (var filestream = new FileStream(APKFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == fileResourceLocation)
                        {
                            string fileLocation = Path.Combine(FilePathToSave, string.Format("{0}-{1}", index, fileResourceLocation.Split(Convert.ToChar(@"/")).Last()));
                            using (Stream strm = zipfile.GetInputStream(item))
                            using (FileStream output = File.Create(fileLocation))
                            {
                                try
                                {
                                    strm.CopyTo(output);
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }

                        }
                    }
                }
            }
        }
Example #3
0
        } // End UnZip

        /// <summary>
        /// Unzip a local file and return its contents via streamreader to a local the same location as the ZIP.
        /// </summary>
        /// <param name="zipFile">Location of the zip on the HD</param>
        /// <returns>List of unzipped file names</returns>
        public static List <string> UnzipToFolder(string zipFile)
        {
            //1. Initialize:
            var files     = new List <string>();
            var slash     = zipFile.LastIndexOf(Path.DirectorySeparatorChar);
            var outFolder = "";

            if (slash > 0)
            {
                outFolder = zipFile.Substring(0, slash);
            }
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;

            try
            {
                var fs = File.OpenRead(zipFile);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                foreach (ZipEntry zipEntry in zf)
                {
                    //Ignore Directories
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }

                    //Remove the folder from the entry
                    var entryFileName = Path.GetFileName(zipEntry.Name);
                    if (entryFileName == null)
                    {
                        continue;
                    }

                    var buffer    = new byte[4096];  // 4K is optimum
                    var zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    var fullZipToPath = Path.Combine(outFolder, entryFileName);

                    //Save the file name for later:
                    files.Add(fullZipToPath);
                    //Log.Trace("Data.UnzipToFolder(): Input File: " + zipFile + ", Output Directory: " + fullZipToPath);

                    //Copy the data in buffer chunks
                    using (var streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
            return(files);
        } // End UnZip
 public static void ExtractFileAndSave(string APKFilePath, string fileResourceLocation, string FilePathToSave, int index)
 {
     using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(APKFilePath)))
     {
         using (var filestream = new FileStream(APKFilePath, FileMode.Open, FileAccess.Read))
         {
             ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
             ICSharpCode.SharpZipLib.Zip.ZipEntry item;
             while ((item = zip.GetNextEntry()) != null)
             {
                 if (item.Name.ToLower() == fileResourceLocation)
                 {
                     string fileLocation = Path.Combine(FilePathToSave, string.Format("{0}-{1}", index, fileResourceLocation.Split(Convert.ToChar(@"/")).Last()));
                     using (Stream strm = zipfile.GetInputStream(item))
                         using (FileStream output = File.Create(fileLocation))
                         {
                             try
                             {
                                 strm.CopyTo(output);
                             }
                             catch (Exception ex)
                             {
                                 throw ex;
                             }
                         }
                 }
             }
         }
     }
 }
Example #5
0
        public static void ExtractPackageAppIconIfNotExists(string apkFilePath, string iconStoreDirectory, string packageName)
        {
            Platforms.Android.AndroidManifestData packageData = GetManifestData(apkFilePath);

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath));
            if (!string.IsNullOrEmpty(packageData.ApplicationIconName) && !string.IsNullOrEmpty(packageName))
            {
                XDocument xDocManifest = new XDocument();
                XDocument xDocResource = new XDocument();
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    item = zipfile.GetEntry(packageData.ApplicationIconName);
                    if (item == null)
                    {
                        return;
                    }
                    string fileType = Path.GetExtension(packageData.ApplicationIconName);

                    using (Stream strm = zipfile.GetInputStream(item))
                        using (FileStream output = File.Create(Path.Combine(iconStoreDirectory, packageName + fileType)))
                        {
                            try
                            {
                                strm.CopyTo(output);
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                        }
                }
            }
        }
Example #6
0
        private System.Xml.XmlDocument GetContentXmlFile(ICSharpCode.SharpZipLib.Zip.ZipFile zipFile)
        {
            // Get file(in zip archive) that contains data ("content.xml").
            // ICSharpCode.SharpZipLib.Zip.ZipEntry contentZipEntry = zipFile["content.xml"];

            // Extract that file to MemoryStream.
            // Stream contentStream = new MemoryStream();
            // contentZipEntry.Extract(contentStream);
            // contentStream.Seek(0, SeekOrigin.Begin);

            // Create XmlDocument from MemoryStream (MemoryStream contains content.xml).
            System.Xml.XmlDocument contentXml = new System.Xml.XmlDocument();


            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zipFile.GetEntry("content.xml");
            if (ze == null)
            {
                throw new System.ArgumentException("content.xml not found in Zip");
            } // End if (ze == null)

            using (System.IO.Stream contentStream = zipFile.GetInputStream(ze))
            {
                // do something with ZipInputStream
                contentXml.Load(contentStream);
            } // End Using contentStream

            return(contentXml);
        } // End Function GetContentXmlFile
        }        //

        //
        // =======================================================================================
        /// <summary>
        ///         ''' unzip
        ///         ''' </summary>
        ///         ''' <param name="zipTempPathFilename"></param>
        ///         ''' <param name="addTempPathFilename"></param>
        ///         ''' <remarks></remarks>
        public static void zipTempCdnFile(CPBaseClass cp, string zipTempPathFilename, List <string> addTempPathFilename)
        {
            try {
                ICSharpCode.SharpZipLib.Zip.ZipFile z;
                if (cp.TempFiles.FileExists(zipTempPathFilename))
                {
                    //
                    // update existing zip with list of files
                    z = new ICSharpCode.SharpZipLib.Zip.ZipFile(cp.TempFiles.PhysicalFilePath + zipTempPathFilename);
                }
                else
                {
                    //
                    // create new zip
                    z = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(cp.TempFiles.PhysicalFilePath + zipTempPathFilename);
                }
                z.BeginUpdate();
                foreach (var pathFilename in addTempPathFilename)
                {
                    z.Add(cp.TempFiles.PhysicalFilePath + pathFilename, System.IO.Path.GetFileName(pathFilename));
                }
                z.CommitUpdate();
                z.Close();
            } catch (Exception ex) {
                cp.Site.ErrorReport(ex);
            }
        }
Example #8
0
        public static SharpZipLibResult ReadWithSharpZipLib(MemoryStream stream)
        {
            stream.Position = 0;

            try
            {
                using (var file = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream))
                {
                    file.IsStreamOwner = false;
                    var data = file
                               .Cast <ICSharpCode.SharpZipLib.Zip.ZipEntry>()
                               .Select(x => new SharpZipLibEntry(x))
                               .ToList();

                    return(new SharpZipLibResult
                    {
                        Success = true,
                        Data = data,
                    });
                }
            }
            catch (Exception e)
            {
                return(new SharpZipLibResult
                {
                    Success = false,
                    Exception = e,
                });
            }
        }
        private static string ExtractZip(FileInfo info)
        {
            var extractDir = Path.Combine(info.Directory.FullName, info.Name.Substring(0, info.Name.Length - info.Extension.Length));
            if (!Directory.Exists(extractDir)) Directory.CreateDirectory(extractDir);

            var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(info.FullName);
            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zip)
            {
                var dst = Path.Combine(extractDir, entry.Name.Replace('/', Path.DirectorySeparatorChar));
                if (File.Exists(dst)) File.Delete(dst);

                var inf = new FileInfo(dst);
                if (!inf.Directory.Exists) inf.Directory.Create();

                using (var zipStream = zip.GetInputStream(entry))
                {
                    using (var output = File.OpenWrite(dst))
                    {
                        var buffer = new byte[4096];

                        while (zipStream.Position < entry.Size)
                        {
                            var read = zipStream.Read(buffer, 0, buffer.Length);
                            if (read > 0) output.Write(buffer, 0, read);
                            else break;
                        }
                    }
                }
            }
            zip.Close();

            return extractDir;
        }
Example #10
0
        } // End Function thisResourceName

        /// <summary>
        /// Writes DataSet as .ods file.
        /// </summary>
        /// <param name="odsFile">DataSet that represent .ods file.</param>
        /// <param name="outputFilePath">The name of the file to save to.</param>
        public void WriteOdsFile(System.Data.DataSet odsFile, string outputFilePath)
        {
            //this.GetZipFile(Assembly.GetExecutingAssembly().GetManifestResourceStream("OdsReadWrite.template.ods"));

            using (System.IO.Stream iss = GetTemplateStream("template.ods"))
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipFile templateFile =
                           new ICSharpCode.SharpZipLib.Zip.ZipFile(iss))
                {
                    System.Xml.XmlDocument contentXml =
                        this.GetContentXmlFile(templateFile);

                    System.Xml.XmlNamespaceManager nmsManager =
                        this.InitializeXmlNamespaceManager(contentXml);

                    System.Xml.XmlNode sheetsRootNode = this.GetSheetsRootNodeAndRemoveChildrens(contentXml, nmsManager);

                    foreach (System.Data.DataTable sheet in odsFile.Tables)
                    {
                        this.SaveSheet(sheet, sheetsRootNode);
                    }

                    using (System.IO.FileStream fs =
                               System.IO.File.OpenWrite(outputFilePath))
                    {
                        using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOut =
                                   new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs))
                        {
                            SaveFromTemplate(templateFile, zipOut, contentXml);
                        } // end using zipOut
                    }     // End using fs
                }         // End using templateFile
            }             // End using iss
        }                 // End Sub WriteOdsFile
Example #11
0
        /// <summary>
        /// 根据所选文件打包下载
        /// 编写日期:2018/2/22
        /// 编写人:郑亚波
        /// </summary>
        /// <param name="response"></param>
        /// <param name="files"></param>
        /// <param name="zipFileName"></param>
        public void Download(System.Web.HttpResponse response, IEnumerable <string> files, string zipFileName)
        {
            //根据所选文件打包下载
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] buffer             = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms))
            {
                file.BeginUpdate();
                file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。

                foreach (var item in files)
                {
                    if (System.IO.File.Exists(item.ToString()))
                    {
                        file.Add(item);
                    }
                }
                file.CommitUpdate();
                buffer      = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
            }
            response.AddHeader("content-disposition", "attachment;filename=" + zipFileName);
            response.BinaryWrite(buffer);
            response.Flush();
            response.End();
        }
Example #12
0
        void lv3_DoubleClick(object sender, EventArgs e)
        {
            ListViewItem lvi = lv3.SelectedItems[0];
            ArrayList    al  = (ArrayList)lvi.Tag;
            FileInfo     fi  = (FileInfo)al[0];

            zip.Zip.ZipFile  zf = (zip.Zip.ZipFile)al[1];
            zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)al[2];

            string strFName = fi.FullName;

            string strName   = ze.Name;
            string strParent = "";

            if (strName.IndexOf("/") != -1)
            {
                string[] strNameArr = strName.Split(Encoding.Default.GetChars(Encoding.Default.GetBytes("/")));
                strName = strNameArr[strNameArr.Length - 1];
                for (int i = 0; i < strNameArr.Length - 2; i++)
                {
                    strParent += "\\" + strNameArr[i];
                }
            }

            if (isZip(strFName))
            {
                zip.Zip.FastZip fz = new ICSharpCode.SharpZipLib.Zip.FastZip();
                fz.ExtractZip(strFName, Application.UserAppDataPath + strParent, ze.Name);

                FileInfo[] fins = new FileInfo[1];
                fins.SetValue(new FileInfo(Application.UserAppDataPath + "\\" + ze.Name), 0);
                PropForm pf = new PropForm(fins);
                pf.Show();
            }
        }
Example #13
0
        private Hashtable searchInCompressed(FileInfo fi, string in_searchstring)
        {
            Hashtable ht_ret = new Hashtable();

            if (fi.Extension.ToLower().Equals(".zip"))
            {
                zip.Zip.ZipFile zf     = new ICSharpCode.SharpZipLib.Zip.ZipFile(fi.FullName);
                IEnumerator     ienumk = zf.GetEnumerator();
                ienumk.MoveNext();

                do
                {
                    GC.Collect();
                    Application.DoEvents();

                    try
                    {
                        zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)ienumk.Current;
                        if (ze.Name.ToLower().IndexOf(in_searchstring) != -1)
                        {
                            ht_ret.Add(ht_ret.Count, ze);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                } while (ienumk.MoveNext());
            }
            return(ht_ret);
        }
        public static void ExtractPackageAppIconIfNotExists(string apkFilePath, string iconStoreDirectory, string packageName)
        {
            Platforms.Android.AndroidManifestData packageData = GetManifestData(apkFilePath);

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath));
            if (!string.IsNullOrEmpty(packageData.ApplicationIconName) && !string.IsNullOrEmpty(packageName))
            {
                XDocument xDocManifest = new XDocument();
                XDocument xDocResource = new XDocument();
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    item = zipfile.GetEntry(packageData.ApplicationIconName);
                    if (item == null)
                        return;
                    string fileType = Path.GetExtension(packageData.ApplicationIconName);

                    using (Stream strm = zipfile.GetInputStream(item))
                    using (FileStream output = File.Create(Path.Combine(iconStoreDirectory, packageName + fileType)))
                    {
                        try
                        {
                            strm.CopyTo(output);
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                }
          

            }
        }
Example #15
0
        public static bool UpdateEntry(string zipFileName, string entryname, byte[] buffer, string password = null)
        {
            try
            {
                string dir     = Path.GetDirectoryName(zipFileName);
                string tmpfile = Path.Combine(dir, entryname + ".tmp");
                if (File.Exists(tmpfile))
                {
                    File.Delete(tmpfile);
                }
                FileStream streamWriter = File.Create(tmpfile);
                streamWriter.Write(buffer, 0, buffer.Length);
                SharpZipLib.Zip.ZipFile s = new SharpZipLib.Zip.ZipFile(zipFileName);
                s.Password = password;

                SharpZipLib.Zip.StaticDiskDataSource data = new SharpZipLib.Zip.StaticDiskDataSource(tmpfile);
                s.BeginUpdate();
                s.Add(data, entryname);
                s.CommitUpdate();
                s.Close();
                streamWriter.Close();
                if (File.Exists(tmpfile))
                {
                    File.Delete(tmpfile);
                }
                return(true);
            }
            catch (Exception e)
            {
                LogUtil.LogError(e.Message);
                return(false);
            }
        }
Example #16
0
 /// <summary>
 /// Cria a instanci com os dados contidos na stream informada.
 /// </summary>
 /// <param name="inStream">Stream contendo os dados do pacote.</param>
 public DataEntryPackage(System.IO.Stream inStream)
 {
     _inStream = inStream;
     if (inStream != null)
     {
         _zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(inStream);
     }
 }
Example #17
0
 public Package(ICSCZL.Zip.ZipFile zFile, SetupInfo pkgConfg)
 {
     zipFile   = zFile;
     pkgConfig = pkgConfg;
     dfnFiles  = new Hashtable();
     jsFiles   = new Hashtable();
     Parse();
 }
Example #18
0
 public void Release()
 {
     if (zip != null)
     {
         zip.Close();
         zip = null;
     }
     isValid = false;
 }
Example #19
0
        private void DoExtract(
            IPreprocessingStepCallback callback,
            string specificFileToExtract,
            Func <PreprocessingStepParams, bool> onNext,
            string password)
        {
            using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(@params.Location))
            {
                if (password != null)
                {
                    zipFile.Password = password;
                }
                var entriesToEnum = specificFileToExtract != null?
                                    Enumerable.Repeat(zipFile.GetEntry(specificFileToExtract), 1) : zipFile.OfType <ICSharpCode.SharpZipLib.Zip.ZipEntry>();

                foreach (var entry in entriesToEnum.Where(e => e != null))
                {
                    if (entry.IsDirectory)
                    {
                        continue;
                    }

                    if (entry.IsCrypted && password == null)
                    {
                        throw new PasswordException();
                    }

                    string entryFullPath = @params.FullPath + "\\" + entry.Name;
                    string tmpFileName   = callback.TempFilesManager.GenerateNewName();

                    callback.SetStepDescription("Unpacking " + entryFullPath);
                    using (FileStream tmpFs = new FileStream(tmpFileName, FileMode.CreateNew))
                        using (var entryProgress = progressAggregator.CreateProgressSink())
                        {
                            using (var entryStream = zipFile.GetInputStream(entry))
                            {
                                var totalLen = entry.Size;
                                IOUtils.CopyStreamWithProgress(entryStream, tmpFs, pos =>
                                {
                                    if (totalLen > 0)
                                    {
                                        callback.SetStepDescription($"Unpacking {pos * 100 / totalLen}%: {entryFullPath}");
                                        entryProgress.SetValue((double)pos / totalLen);
                                    }
                                }, callback.Cancellation);
                            }
                        }

                    if (!onNext(new PreprocessingStepParams(tmpFileName, entryFullPath,
                                                            @params.PreprocessingHistory.Add(new PreprocessingHistoryItem(name, entry.Name)))))
                    {
                        break;
                    }
                }
            }
        }
        protected void ButtonSenadores_Click(object sender, EventArgs e)
        {
            String atualDir = Server.MapPath("Upload");

            if (FileUpload.FileName != "")
            {
                FileUpload.SaveAs(atualDir + "//" + FileUpload.FileName);

                ICSharpCode.SharpZipLib.Zip.ZipFile file = null;

                try
                {
                    file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "//" + FileUpload.FileName);

                    if (file.TestArchive(true) == false)
                    {
                        Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>");
                        return;
                    }
                }
                finally
                {
                    if (file != null)
                    {
                        file.Close();
                    }
                }

                ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null);

                File.Delete(atualDir + "//" + FileUpload.FileName);

                CarregarSenadores(atualDir);
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(atualDir);

                foreach (FileInfo file in dir.GetFiles("*.zip"))
                {
                    ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
                    zip.ExtractZip(file.FullName, file.DirectoryName, null);

                    File.Delete(file.FullName);

                    CarregarSenadores(file.DirectoryName);
                }
            }

            Cache.Remove("menorAnoSenadores");
            Cache.Remove("ultimaAtualizacaoSenadores");
            Cache.Remove("tableSenadores");
            Cache.Remove("tableDespesaSenadores");
            Cache.Remove("tablePartidoSenadores");
        }
Example #21
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Tag == null)
            {
                return;
            }

            if (e.Node.Tag.ToString() == "FILE" || e.Node.Tag.ToString() == "ZIP")
            {
                LearnLifeCore.FileReader.FileReader fileReader = new LearnLifeCore.FileReader.FileReader();
                fileReader.Border = LearnLifeWin.Properties.Settings.Default.ReadFileBorder;
                string filename = e.Node.Name;

                if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT")
                {
                    OpenFile = string.Empty;

                    filename = Path.Combine(Path.GetTempPath(), e.Node.Text);

                    ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
                    try
                    {
                        FileStream fs = File.OpenRead(e.Node.Parent.Parent.Name);
                        zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                        byte[] buffer    = new byte[4096];
                        Stream zipStream = zf.GetInputStream(zf.GetEntry(e.Node.Name));
                        using (FileStream streamWriter = File.Create(filename))
                        {
                            ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                    finally
                    {
                        if (zf != null)
                        {
                            zf.IsStreamOwner = true;                // Makes close also shut the underlying stream
                            zf.Close();                             // Ensure we release resources
                        }
                    }
                }
                else
                {
                    isModified = false;
                    OpenFile   = filename;
                }

                ReadLifeFile(fileReader, filename);

                if (e.Node.Tag.ToString() == "ZIP" && e.Node.Parent.Parent.Tag.ToString() == "ZIPROOT")
                {
                    File.Delete(filename);
                }
            }
        }
Example #22
0
 public ZipFile(
     ICSharpCode.SharpZipLib.Zip.ZipEntry zipArchiveEntry,
     ICSharpCode.SharpZipLib.Zip.ZipFile zipArchive,
     string path, string zipPath,
     ZipOption zipOption = null) : base(path, "zip")
 {
     _zipArchiveEntry = zipArchiveEntry;
     _zipArchive      = zipArchive;
     _zipOption       = zipOption ?? new ZipOption();
     ZipPath          = zipPath;
 }
        ZipFile(Stream stream, ICSharpCode.SharpZipLib.Zip.ZipFile zipFile)
        {
            if (zipFile == null)
                throw new ArgumentNullException("zipFile", "zipFile is null.");
            if (stream == null)
                throw new ArgumentNullException("stream", "stream is null.");


            _stream = stream;
            _zipFile = zipFile;
            _zipFile.BeginUpdate();
        }
Example #24
0
        private static void ZipFilesInDir(DirectoryInfo dirinfDirToZip, ICSharpCode.SharpZipLib.Zip.ZipFile NewMapZipped)
        {
            foreach (DirectoryInfo dirinfSubFolder in dirinfDirToZip.GetDirectories())
            {
                ZipFilesInDir(dirinfSubFolder, NewMapZipped);
            }

            foreach (FileInfo finfMapFile in dirinfDirToZip.GetFiles())
            {
                NewMapZipped.Add(finfMapFile.FullName.Remove(0, finfMapFile.FullName.IndexOf("\\Maps") + 1));
            }
        }
Example #25
0
        private void SelectAPK(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            packageNameLBL.Text    = "Package Name: LENDO ARQUIVO";
            openFileDialog1.Filter = "APK Files|*.APK";
            openFileDialog1.Title  = "Selecione um arquivo .APK";
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                NomeAPK = openFileDialog1.FileName;
                using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(openFileDialog1.FileName)))
                {
                    using (var filestream = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read))
                    {
                        ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                        ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                        try
                        {
                            while ((item = zip.GetNextEntry()) != null)
                            {
                                if (item.Name.ToLower() == "androidmanifest.xml")
                                {
                                    manifestData = new byte[50 * 1024];
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        strm.Read(manifestData, 0, manifestData.Length);
                                    }
                                }
                                if (item.Name.ToLower() == "resources.arsc")
                                {
                                    using (Stream strm = zipfile.GetInputStream(item))
                                    {
                                        using (BinaryReader s = new BinaryReader(strm))
                                        {
                                            resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                ApkReader apkReader = new ApkReader();
                ApkInfo   info      = apkReader.extractInfo(manifestData, resourcesData);
                packageNameLBL.Text   = "Package Name: " + info.packageName;
                versionLBL.Text       = "Version: " + info.versionName;
                installAPKBTN.Enabled = true;
            }
        }
Example #26
0
        internal static void ZipTempMapFiles(string strDestMapNameAndPath)
        {
            ICSharpCode.SharpZipLib.Zip.ZipFile NewMapZipped = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(strDestMapNameAndPath);

            NewMapZipped.BeginUpdate();

            ZipFilesInDir(new DirectoryInfo(MAPS_INITIAL_DIR), NewMapZipped);

            //NewMapZipped.Add(@"Maps\Multiplayer\"+"\\"+);
            //NewMapZipped.Add(@"Maps\Multiplayer\TestMap\GroundTerrain.bin");
            NewMapZipped.CommitUpdate();
            NewMapZipped.Close();
        }
Example #27
0
 public string[] ZIPContents(string SourceFile)
 {
     System.Collections.ArrayList        contents = new System.Collections.ArrayList();
     ICSharpCode.SharpZipLib.Zip.ZipFile zip      = new ICSharpCode.SharpZipLib.Zip.ZipFile(SourceFile);
     for (int i = 0; i < zip.Size; i++)
     {
         if (!zip[i].IsDirectory)
         {
             contents.Add(zip[i].Name);
         }
     }
     return((string[])contents.ToArray(Type.GetType("System.String")));
 }
        public ZipFile()
        {
            _stream = new MemoryStream();
#if NETFX_CORE
            _zipArchive = new ZipArchive(_stream, ZipArchiveMode.Create, true);
#else
            _zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(_stream)
            {
                IsStreamOwner = false,
            };
            _zipFile.BeginUpdate();
#endif
        }
Example #29
0
 protected ZipFileReference CreateZipFileReference(string path)
 {
     ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(System.IO.Path.Combine(Source, path.Substring(1)));
     lock (zipFiles)
     {
         ZipFileReference zipFileRef = new ZipFileReference();
         zipFiles.Add(path, zipFileRef);
         zipFileRef.Path = path;
         zipFileRef.RefCount++;
         zipFileRef.ZipFile = zipFile;
         return(zipFileRef);
     }
 }
Example #30
0
        public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder)
        {
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(archiveFilenameIn);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);
                if (!String.IsNullOrEmpty(password))
                {
                    zf.Password = password;     // AES encrypted entries are handled automatically
                }
                foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;           // Ignore directories
                    }
                    String entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    byte[] buffer    = new byte[4096];  // 4K is optimum
                    Stream zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(outFolder, entryFileName);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Example #31
0
        public static EntryData GetEntryDataFromPatchFile(string filepath, DataHelper dataHelper)
        {
            byte[]     bytesBattleConditionals, bytesWorldConditionals, bytesEvents;
            EntryBytes defaultEntryBytes = dataHelper.LoadDefaultEntryBytes();

            using (ICSharpCode.SharpZipLib.Zip.ZipFile file = new ICSharpCode.SharpZipLib.Zip.ZipFile(filepath))
            {
                bytesBattleConditionals = PatcherLib.Utilities.Utilities.GetZipEntry(file, DataHelper.EntryNameBattleConditionals, false) ?? defaultEntryBytes.BattleConditionals;
                bytesWorldConditionals  = PatcherLib.Utilities.Utilities.GetZipEntry(file, DataHelper.EntryNameWorldConditionals, false) ?? defaultEntryBytes.WorldConditionals;
                bytesEvents             = PatcherLib.Utilities.Utilities.GetZipEntry(file, DataHelper.EntryNameEvents, false) ?? defaultEntryBytes.Events;
            }

            return(dataHelper.LoadEntryDataFromBytes(bytesBattleConditionals, bytesWorldConditionals, bytesEvents));
        }
Example #32
0
        private int FindZipEntry(ICSharpCode.SharpZipLib.Zip.ZipFile file, string path)
        {
            string p = path.Replace('\\', '/');

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in file)
            {
                if (ze.Name.Replace('\\', '/').Equals(p))
                {
                    return((int)ze.ZipFileIndex);
                }
            }

            return(-1);
        }
Example #33
0
 public ZipSystem(string zipFileName, string password = null)
 {
     try
     {
         zip          = new SharpZipLib.Zip.ZipFile(File.OpenRead(zipFileName));
         zip.Password = password;
         isValid      = true;
     }
     catch (Exception e)
     {
         isValid = false;
         LogUtil.LogException(e);
     }
 }
        private static string ExtractZip(FileInfo info)
        {
            var extractDir = Path.Combine(info.Directory.FullName, info.Name.Substring(0, info.Name.Length - info.Extension.Length));

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

            var zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(info.FullName);

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zip)
            {
                var dst = Path.Combine(extractDir, entry.Name.Replace('/', Path.DirectorySeparatorChar));
                if (File.Exists(dst))
                {
                    File.Delete(dst);
                }

                var inf = new FileInfo(dst);
                if (!inf.Directory.Exists)
                {
                    inf.Directory.Create();
                }

                using (var zipStream = zip.GetInputStream(entry))
                {
                    using (var output = File.OpenWrite(dst))
                    {
                        var buffer = new byte[4096];

                        while (zipStream.Position < entry.Size)
                        {
                            var read = zipStream.Read(buffer, 0, buffer.Length);
                            if (read > 0)
                            {
                                output.Write(buffer, 0, read);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            zip.Close();

            return(extractDir);
        }
Example #35
0
        //private static void CopyStream(Stream input, Stream output)
        //{
        //    byte[] buffer = new byte[8 * 1024];
        //    int len;
        //    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        //    {
        //        output.Write(buffer, 0, len);
        //    }
        //}
        public static AndroidManifestData GetManifestData(String apkFilePath)
        {
            byte[] manifestData  = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath)))
            {
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile  zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }
                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);
                                }
                            }
                        }
                    }
                }
            }

            Iteedee.ApkReader.ApkReader reader = new ApkReader.ApkReader();

            Iteedee.ApkReader.ApkInfo info = reader.extractInfo(manifestData, resourcesData);
            string AppName = info.label;


            return(new AndroidManifestData()
            {
                VersionCode = info.versionCode,
                VersionName = info.versionName,
                PackageName = info.packageName,
                ApplicationName = info.label,
                ApplicationIconName = GetBestIconAvailable(info.iconFileNameToGet)
            });
        }
        public void OpenWriteTestZipAddTwo()
        {
            var fn   = "WriteText4.Zip";
            var path = UnitTestInitializeCsv.GetTestPath(fn);

            // Create two files
            WriteFile(fn, "Test", "Test.txt", false);
            WriteFile(fn, "Test", "Test2.txt", false);

            using (var zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(File.OpenRead(path)))
            {
                Assert.AreEqual(2, zipFile.Count);
            }
            FileSystemUtils.FileDelete(path);
        }
Example #37
0
        private static Dictionary<string,object> GetIpaPList(string filePath)
        {
            Dictionary<string, object> plist = new Dictionary<string, object>();
            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(filePath));
            using (var filestream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                ICSharpCode.SharpZipLib.Zip.ZipEntry item;


                while ((item = zip.GetNextEntry()) != null)
                {
                    Match match = Regex.Match(item.Name.ToLower(), @"Payload/([A-Za-z0-9\-. ]+)\/info.plist$", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        byte[] bytes = new byte[50 * 1024];

                        using( Stream strm = zipfile.GetInputStream(item))
                        {
                            int size = strm.Read(bytes, 0, bytes.Length);

                            using (BinaryReader s = new BinaryReader(strm))
                            {
                                byte[] bytes2 = new byte[size];
                                Array.Copy(bytes, bytes2, size);
                                plist = (Dictionary<string, object>)PlistCS.readPlist(bytes2);
                            }
                        }
                       

                        break;
                    }

                }




            }
            return plist;
        }
Example #38
0
        public void Dispose()
        {
            if (m_zip != null)
            {
                if (m_zip.IsUpdating)
                    m_zip.CommitUpdate();
                m_zip.Close();

            #if SHARPZIPLIBWORKS
                //This breaks, because the updates are not flushed correctly
                m_zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(m_zip.Name);
                m_zip.Close();
            #endif
            }
            m_zip = null;

            #if !SHARPZIPLIBWORKS
            if (m_stream != null)
            {
                m_stream.Flush();
                m_stream.Finish();
                m_stream.Close();
            }
            #endif
        }
Example #39
0
 public StreamWrapper(Core.TempFile file, string filename, ICSharpCode.SharpZipLib.Zip.ZipFile zip)
     : base(System.IO.File.Create(file))
 {
     m_file = file;
     m_zip = zip;
     m_filename = filename;
 }
        public static ZipFile Read(Stream zipStream)
        {
            if (zipStream == null)
                throw new ArgumentNullException("zipStream", "zipStream is null.");

#if NETFX_CORE
            var archive = new ZipArchive(zipStream, ZipArchiveMode.Read);
            var zipFile = new ZipFile(zipStream, archive);

            return zipFile;
#else
            var sharpZipLibFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipStream)
            {
                IsStreamOwner = false,
            };
            var zipFile = new ZipFile(zipStream, sharpZipLibFile);

            return zipFile;
#endif
        }
Example #41
0
 public TZipArchive(Stream s)
 {
     zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(s);
 }
Example #42
0
        private void AddZipInfo(FileInfo in_fi, ListView in_lv)
        {
            zip.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(in_fi.FullName);
            IEnumerator ienumk = zf.GetEnumerator();
            ienumk.MoveNext();

            do
            {
                GC.Collect();
                Application.DoEvents();

                try
                {
                    zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)ienumk.Current;
                    if (ze.IsFile)
                    {
                        string strName = ze.Name;
                        string strParent = in_fi.Name;

                        if (strName.IndexOf("/") != -1)
                        {
                            string[] strNameArr = strName.Split(Encoding.Default.GetChars(Encoding.Default.GetBytes("/")));
                            strName = strNameArr[strNameArr.Length-1];
                            strParent += "\\" + strNameArr[strNameArr.Length - 2];
                        }
                        ListViewItem lvi = in_lv.Items.Add(strName);
                        lvi.SubItems.Add(strParent);
                        lvi.SubItems.Add(getRealSize(ze.Size));
                        lvi.SubItems.Add(ze.DateTime.ToShortDateString() + " " + ze.DateTime.ToLongTimeString());

                        ArrayList al = new ArrayList();
                        al.Add(in_fi);
                        al.Add(zf);
                        al.Add(ze);
                        lvi.Tag = al;

                    }


                }
                catch (Exception ex)
                {
                }
            } while (ienumk.MoveNext());
        }
        public void Save(Stream outputStream)
        {
            if (outputStream == null)
                throw new ArgumentNullException("outputStream", "outputStream is null.");

            AssertIsOpen();

#if NETFX_CORE
            var mode = _zipArchive.Mode;
            _zipArchive.Dispose();

            _stream.Position = 0;
            _stream.CopyTo(outputStream);
            _stream.Position = 0;

            _zipArchive = new ZipArchive(_stream, mode);
#else
            _zipFile.CommitUpdate();
            _zipFile.Close();
            ((IDisposable)_zipFile).Dispose();
            _zipFile = null;

            var position = _stream.Position;
            _stream.Position = 0;
            var buffer = new byte[256];
            for (int i = 0, read = 0; i < _stream.Length; i += read)
            {
                read = _stream.Read(buffer, i, buffer.Length);

                if (read > 0)
                    outputStream.Write(buffer, 0, read);
            }
            _stream.Position = position;

            _zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(_stream)
            {
                IsStreamOwner = false,
            };
#endif
        }
Example #44
0
		protected void ButtonSenadores_Click(object sender, EventArgs e)
		{
			String atualDir = Server.MapPath("Upload");

			if (FileUpload.FileName != "")
			{
				FileUpload.SaveAs(atualDir + "//" + FileUpload.FileName);

				ICSharpCode.SharpZipLib.Zip.ZipFile file = null;

				try
				{
					file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "//" + FileUpload.FileName);

					if (file.TestArchive(true) == false)
					{
						Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>");
						return;
					}
				}
				finally
				{
					if (file != null)
						file.Close();
				}

				ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
				zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null);

				File.Delete(atualDir + "//" + FileUpload.FileName);

				CarregarSenadores(atualDir);
			}
			else
			{
				DirectoryInfo dir = new DirectoryInfo(atualDir);

				foreach (FileInfo file in dir.GetFiles("*.zip"))
				{
					ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
					zip.ExtractZip(file.FullName, file.DirectoryName, null);

					File.Delete(file.FullName);

					CarregarSenadores(file.DirectoryName);
				}
			}

			Cache.Remove("menorAnoSenadores");
			Cache.Remove("ultimaAtualizacaoSenadores");
			Cache.Remove("tableSenadores");
			Cache.Remove("tableDespesaSenadores");
			Cache.Remove("tablePartidoSenadores");
		}
        public static ApkInfo ReadApkFromPath(string path)
        {
            byte[] manifestData = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(path)))
            {
                using (var filestream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }

                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);

                                }
                            }
                        }
                    }
                }
            }

            ApkReader apkReader = new ApkReader();
            ApkInfo info = apkReader.extractInfo(manifestData, resourcesData);
            Console.WriteLine(string.Format("Package Name: {0}", info.packageName));
            Console.WriteLine(string.Format("Version Name: {0}", info.versionName));
            Console.WriteLine(string.Format("Version Code: {0}", info.versionCode));

            Console.WriteLine(string.Format("App Has Icon: {0}", info.hasIcon));
            if(info.iconFileName.Count > 0)
                Console.WriteLine(string.Format("App Icon: {0}", info.iconFileName[0]));
            Console.WriteLine(string.Format("Min SDK Version: {0}", info.minSdkVersion));
            Console.WriteLine(string.Format("Target SDK Version: {0}", info.targetSdkVersion));

            if (info.Permissions != null && info.Permissions.Count > 0)
            {
                Console.WriteLine("Permissions:");
                info.Permissions.ForEach(f =>
                {
                    Console.WriteLine(string.Format("   {0}", f));
                });
            }
            else
                Console.WriteLine("No Permissions Found");

            Console.WriteLine(string.Format("Supports Any Density: {0}", info.supportAnyDensity));
            Console.WriteLine(string.Format("Supports Large Screens: {0}", info.supportLargeScreens));
            Console.WriteLine(string.Format("Supports Normal Screens: {0}", info.supportNormalScreens));
            Console.WriteLine(string.Format("Supports Small Screens: {0}", info.supportSmallScreens));
            return info;
        }
Example #46
0
        private void SaveResourceData_Click(object sender, EventArgs e)
        {
            try
            {
                if (ResourceDataFileList.SelectedItems.Count != 1 || ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem == null)
                    return;

                SaveResourceDataFile.FileName = System.IO.Path.GetFileName((ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).Filename);

                if (SaveResourceDataFile.ShowDialog(this) != DialogResult.OK)
                    return;

                if ((ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).Filename == SaveResourceDataFile.FileName)
                    return;

                if ((ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).EntryType == EntryTypeEnum.Regular)
                {
                    using(ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(m_filename))
                    {
                        int index = FindZipEntry(zipfile, (ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).Filename);
                        if (index >= 0)
                            using (System.IO.FileStream fs = new System.IO.FileStream(SaveResourceDataFile.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                                Utility.CopyStream(zipfile.GetInputStream(index), fs);
                    }
                }
                else if ((ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).EntryType == EntryTypeEnum.Added)
                {
                    System.IO.File.Copy((ResourceDataFileList.SelectedItems[0].Tag as ResourceDataItem).Filename, SaveResourceDataFile.FileName, true);
                }
            }
            catch (Exception ex)
            {
                string msg = NestedExceptionMessageProcessor.GetFullMessage(ex);
                MessageBox.Show(this, string.Format(Strings.FileCopyError, ex.Message), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #47
0
		private void btnExport_Click(object sender, EventArgs e)
		{
			//acquire target
			var sfd = new SaveFileDialog();
			sfd.Filter = "XRNS (*.xrns)|*.xrns";
			if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
				return;

			//configuration:
			var outPath = sfd.FileName;
			string templatePath = Path.Combine(Path.GetDirectoryName(outPath), "template.xrns");
			int configuredPatternLength = int.Parse(txtPatternLength.Text);


			//load template
			MemoryStream msSongXml = new MemoryStream();
			var zfTemplate = new ICSharpCode.SharpZipLib.Zip.ZipFile(templatePath);
			{
				int zfSongXmlIndex = zfTemplate.FindEntry("Song.xml", true);
				using (var zis = zfTemplate.GetInputStream(zfTemplate.GetEntry("Song.xml")))
				{
					byte[] buffer = new byte[4096];     // 4K is optimum
					ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(zis, msSongXml, buffer);
				}
			}
			XElement templateRoot = XElement.Parse(System.Text.Encoding.UTF8.GetString(msSongXml.ToArray()));

			//get the pattern pool, and whack the child nodes
			var xPatterns = templateRoot.XPathSelectElement("//Patterns");
			var xPatternPool = xPatterns.Parent;
			xPatterns.Remove();

			var writer = new StringWriter();
			writer.WriteLine("<Patterns>");


			int pulse0_lastNote = -1;
			int pulse0_lastType = -1;
			int pulse1_lastNote = -1;
			int pulse1_lastType = -1;
			int tri_lastNote = -1;
			int noise_lastNote = -1;

			int patternCount = 0;
			int time = 0;
			while (time < Log.Count)
			{
				patternCount++;

				//begin writing pattern: open the tracks list
				writer.WriteLine("<Pattern>");
				writer.WriteLine("<NumberOfLines>{0}</NumberOfLines>", configuredPatternLength);
				writer.WriteLine("<Tracks>");

				//write the pulse tracks
				for (int TRACK = 0; TRACK < 2; TRACK++)
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					int lastNote = TRACK == 0 ? pulse0_lastNote : pulse1_lastNote;
					int lastType = TRACK == 0 ? pulse0_lastType : pulse1_lastType;
					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						PulseState pulse = new PulseState();
						if (TRACK == 0) pulse = rec.pulse0;
						if (TRACK == 1) pulse = rec.pulse1;

						//transform quieted notes to dead notes
						//blech its buggy, im tired
						//if (pulse.vol == 0)
						//  pulse.en = false;

						bool keyoff = false, keyon = false;
						if (lastNote != -1 && !pulse.en)
						{
							lastNote = -1;
							lastType = -1;
							keyoff = true;
						}
						else if (lastNote != pulse.note && pulse.en)
							keyon = true;

						if (lastType != pulse.type && pulse.note != -1)
							keyon = true;

						if (pulse.en)
						{
							lastNote = pulse.note;
							lastType = pulse.type;
						}

						writer.WriteLine("<Line index=\"{0}\">", patLine);
						writer.WriteLine("<NoteColumns>");
						writer.WriteLine("<NoteColumn>");
						if (keyon)
						{
							writer.WriteLine("<Note>{0}</Note>", NameForNote(pulse.note));
							writer.WriteLine("<Instrument>{0:X2}</Instrument>", pulse.type);
						}
						else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

						if(lastNote != -1)
							writer.WriteLine("<Volume>{0:X2}</Volume>", pulse.vol * 8);

						writer.WriteLine("</NoteColumn>");
						writer.WriteLine("</NoteColumns>");
						writer.WriteLine("</Line>");
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");

					if (TRACK == 0)
					{
						pulse0_lastNote = lastNote;
						pulse0_lastType = lastType;
					}
					else
					{
						pulse1_lastNote = lastNote;
						pulse1_lastType = lastType;
					}

				} //pulse tracks loop

				//triangle track generation
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						TriangleState tri = rec.triangle;

						{
							bool keyoff = false, keyon = false;
							if (tri_lastNote != -1 && !tri.en)
							{
								tri_lastNote = -1;
								keyoff = true;
							}
							else if (tri_lastNote != tri.note && tri.en)
								keyon = true;

							if(tri.en)
								tri_lastNote = tri.note;

							writer.WriteLine("<Line index=\"{0}\">", patLine);
							writer.WriteLine("<NoteColumns>");
							writer.WriteLine("<NoteColumn>");
							if (keyon)
							{
								writer.WriteLine("<Note>{0}</Note>", NameForNote(tri.note));
								writer.WriteLine("<Instrument>08</Instrument>");
							}
							else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

							//no need for tons of these
							//if(keyon) writer.WriteLine("<Volume>80</Volume>");

							writer.WriteLine("</NoteColumn>");
							writer.WriteLine("</NoteColumns>");
							writer.WriteLine("</Line>");
						}
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				}

				//noise track generation
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");

					for (int i = 0; i < configuredPatternLength; i++)
					{
						int patLine = i;

						int index = i + time;
						if (index >= Log.Count) continue;

						var rec = Log[index];

						NoiseState noise = rec.noise;

						//transform quieted notes to dead notes
						//blech its buggy, im tired
						//if (noise.vol == 0)
						//  noise.en = false;

						{
							bool keyoff = false, keyon = false;
							if (noise_lastNote != -1 && !noise.en)
							{
								noise_lastNote = -1;
								keyoff = true;
							}
							else if (noise_lastNote != noise.note && noise.en)
								keyon = true;

							if (noise.en)
								noise_lastNote = noise.note;

							writer.WriteLine("<Line index=\"{0}\">", patLine);
							writer.WriteLine("<NoteColumns>");
							writer.WriteLine("<NoteColumn>");
							if (keyon)
							{
								writer.WriteLine("<Note>{0}</Note>", NameForNote(noise.note));
								writer.WriteLine("<Instrument>04</Instrument>");
							}
							else if (keyoff) writer.WriteLine("<Note>OFF</Note>");

							if (noise_lastNote != -1)
								writer.WriteLine("<Volume>{0:X2}</Volume>", noise.vol * 8);

							writer.WriteLine("</NoteColumn>");
							writer.WriteLine("</NoteColumns>");
							writer.WriteLine("</Line>");
						}
					}

					//close PatternTrack
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				} //noise track generation

				//write empty track for now for pcm
				for (int TRACK = 4; TRACK < 5; TRACK++)
				{
					writer.WriteLine("<PatternTrack type=\"PatternTrack\">");
					writer.WriteLine("<Lines>");
					writer.WriteLine("</Lines>");
					writer.WriteLine("</PatternTrack>");
				}

				//we definitely need a dummy master track now
				writer.WriteLine("<PatternMasterTrack type=\"PatternMasterTrack\">");
				writer.WriteLine("</PatternMasterTrack>");

				//close tracks
				writer.WriteLine("</Tracks>");

				//close pattern
				writer.WriteLine("</Pattern>");

				time += configuredPatternLength;

			} //main pattern loop

			writer.WriteLine("</Patterns>");
			writer.Flush();

			var xNewPatternList = XElement.Parse(writer.ToString());
			xPatternPool.Add(xNewPatternList);

			//write pattern sequence
			writer = new StringWriter();
			writer.WriteLine("<SequenceEntries>");
			for (int i = 0; i < patternCount; i++)
			{
				writer.WriteLine("<SequenceEntry>");
				writer.WriteLine("<IsSectionStart>false</IsSectionStart>");
				writer.WriteLine("<Pattern>{0}</Pattern>", i);
				writer.WriteLine("</SequenceEntry>");
			}
			writer.WriteLine("</SequenceEntries>");

			var xPatternSequence = templateRoot.XPathSelectElement("//PatternSequence");
			xPatternSequence.XPathSelectElement("SequenceEntries").Remove();
			xPatternSequence.Add(XElement.Parse(writer.ToString()));

			//copy template file to target
			File.Delete(outPath);
			File.Copy(templatePath, outPath);

			var msOutXml = new MemoryStream();
			templateRoot.Save(msOutXml);
			msOutXml.Flush();
			msOutXml.Position = 0;
			var zfOutput = new ICSharpCode.SharpZipLib.Zip.ZipFile(outPath);
			zfOutput.BeginUpdate();
			zfOutput.Add(new Stupid { stream = msOutXml }, "Song.xml");
			zfOutput.CommitUpdate();
			zfOutput.Close();

			//for easier debugging, write patterndata XML
			//DUMP_TO_DISK(msOutXml.ToArray())
		}
Example #48
0
 protected ZipFileReference CreateZipFileReference(string path)
 {
     ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(System.IO.Path.Combine(Source, path.Substring(1)));
     lock (zipFiles)
     {
         ZipFileReference zipFileRef = new ZipFileReference();
         zipFiles.Add(path, zipFileRef);
         zipFileRef.Path = path;
         zipFileRef.RefCount++;
         zipFileRef.ZipFile = zipFile;
         return zipFileRef;
     }
 }
Example #49
0
		//protected void Page_Load(object sender, EventArgs e)
		//{
		//    //CifrarStringConexao();
		//    GridViewAcerto.PreRender += GridViewAcerto_PreRender;
		//    GridViewPrevia.PreRender += GridViewPrevia_PreRender;
		//}

		//private void GridViewPrevia_PreRender(object sender, EventArgs e)
		//{
		//    try
		//    {
		//        GridViewPrevia.HeaderRow.TableSection = TableRowSection.TableHeader;
		//    }
		//    catch (Exception)
		//    { }
		//}

		//private void GridViewAcerto_PreRender(object sender, EventArgs e)
		//{
		//    try
		//    {
		//        GridViewAcerto.HeaderRow.TableSection = TableRowSection.TableHeader;
		//    }
		//    catch (Exception)
		//    { }
		//}

		protected void ButtonEnviar_Click(object sender, EventArgs e)
		{
			Cache.Remove("menorAno");
			Cache.Remove("ultima_atualizacao");
			Cache.Remove("tableParlamentar");
			Cache.Remove("tableDespesa");
			Cache.Remove("tablePartido");

			String atualDir = Server.MapPath("Upload");

			if (FileUpload.FileName != "")
			{
				//string ftpUrl = ConfigurationManager.AppSettings["ftpAddress"];
				//string ftpUsername = ConfigurationManager.AppSettings["ftpUsername"];
				//string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"];
				//FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl + "Transactions.zip");
				//request.Proxy = new WebProxy(); //-----The requested FTP command is not supported when using HTTP proxy.
				//request.Method = WebRequestMethods.Ftp.UploadFile;
				//request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
				//StreamReader sourceStream = new StreamReader(fileToBeUploaded);
				//byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
				//sourceStream.Close();
				//request.ContentLength = fileContents.Length;
				//Stream requestStream = request.GetRequestStream();
				//requestStream.Write(fileContents, 0, fileContents.Length);
				//requestStream.Close();
				//FtpWebResponse response = (FtpWebResponse)request.GetResponse();
				//Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
				//response.Close();

				//using (var requestStream = request.GetRequestStream())
				//{
				//    using (var input = File.OpenRead(fileToBeUploaded))
				//    {
				//        input.CopyTo(requestStream);
				//    }
				//}

				if (!Directory.Exists(atualDir))
					Directory.CreateDirectory(atualDir);

				FileUpload.SaveAs(atualDir + "\\" + FileUpload.FileName);

				ICSharpCode.SharpZipLib.Zip.ZipFile file = null;

				try
				{
					file = new ICSharpCode.SharpZipLib.Zip.ZipFile(atualDir + "\\" + FileUpload.FileName);

					if (file.TestArchive(true) == false)
					{
						Response.Write("<script>alert('Erro no Zip. Faça o upload novamente.')</script>");
						return;
					}
				}
				finally
				{
					if (file != null)
						file.Close();
				}

				ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
				zip.ExtractZip(atualDir + "//" + FileUpload.FileName, Server.MapPath("Upload"), null);

				File.Delete(atualDir + "//" + FileUpload.FileName);

				Carregar(atualDir);
			}
			else
			{
				DirectoryInfo dir = new DirectoryInfo(atualDir);

				foreach (FileInfo file in dir.GetFiles("*.zip"))
				{
					ICSharpCode.SharpZipLib.Zip.FastZip zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
					zip.ExtractZip(file.FullName, file.DirectoryName, null);

					File.Delete(file.FullName);

					Carregar(file.DirectoryName);
				}
			}
		}
Example #50
0
        private void ExtractXmlFiles(Stream stream)
        {
#if SILVERLIGHT
            StreamResourceInfo zipStream = new StreamResourceInfo(stream, null);
#else
            ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(stream);
#endif

            foreach (string file in FilesToDownload)
            {
                UpdateProgress(0, "Decompressing " + file + "...");
#if !SILVERLIGHT
                // we don't actually want ClientBin part in the zip
                string part = file.Remove(0, 10);
                StreamReader sr = new StreamReader(zipFile.GetInputStream(zipFile.GetEntry(part)));
                string unzippedFile = sr.ReadToEnd();
                StreamWriter writer = new StreamWriter(file);
                writer.Write(unzippedFile);
                writer.Close();
#else
                Uri part = new Uri(file, UriKind.Relative);
                // This reading method only works in Silverlight due to the GetResourceStream not existing with 2 arguments in
                // regular .Net-land
                StreamResourceInfo fileStream = Application.GetResourceStream(zipStream, part);
                StreamReader sr = new StreamReader(fileStream.Stream);
                string unzippedFile = sr.ReadToEnd();
                //Write it in a special way when using IsolatedStorage, due to IsolatedStorage
                //having a huge performance issue when writing small chunks
                IsolatedStorageFileStream isfs = GetFileStream(file, true);
                    
                char[] charBuffer = unzippedFile.ToCharArray();
                int fileSize = charBuffer.Length;
                byte[] byteBuffer = new byte[fileSize];
                for (int i = 0; i < fileSize; i++) byteBuffer[i] = (byte)charBuffer[i];
                isfs.Write(byteBuffer, 0, fileSize);
                isfs.Close();
#endif

                UpdateProgress(0, "Finished " + file + "...");
            }

#if !SILVERLIGHT
            zipFile.Close();
#endif
        }
Example #51
0
        private Hashtable searchInCompressed(FileInfo fi,string in_searchstring)
        {
            Hashtable ht_ret = new Hashtable();
            if (fi.Extension.ToLower().Equals(".zip"))
            {
                zip.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fi.FullName);
                IEnumerator ienumk = zf.GetEnumerator();
                ienumk.MoveNext();

                do
                {
                    GC.Collect();
                    Application.DoEvents();

                    try
                    {
                        zip.Zip.ZipEntry ze = (zip.Zip.ZipEntry)ienumk.Current;
                        if (ze.Name.ToLower().IndexOf(in_searchstring) != -1)
                        {
                            ht_ret.Add(ht_ret.Count, ze);
                        }


                    }
                    catch (Exception ex)
                    {
                    }
                } while (ienumk.MoveNext());
            }
            return ht_ret;
        }
Example #52
0
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    if (m_zip != null)
                    {
                        m_basestream.Flush();
                        m_basestream.Position = 0;

                        if (!m_zip.IsUpdating)
                            m_zip.BeginUpdate();
                        m_zip.Add(this, m_filename);
                        m_file.Dispose();
                    }
                    m_zip = null;
                }
                base.Dispose(disposing);
            }
Example #53
0
 public TZipArchive(string ZipFile)
 {
     zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(ZipFile);
 }
Example #54
0
        private static void SaveUnCrushedAppIcon(string ipaFilePath, string iconDirectory, string appIdentifier, bool GetRetina)
        {
            Dictionary<string, object> plistInfo = GetIpaPList(ipaFilePath);

            List<string> iconFiles = GetiOSBundleIconNames(plistInfo);

            string fileName = string.Empty;
            if (iconFiles.Count > 1)
            {
                iconFiles.ForEach(f =>
                {
                    if (GetRetina && f.ToLower().Contains("icon@2x"))
                        fileName = f;
                    else if (!GetRetina && !f.ToLower().Contains("icon@2x"))
                        fileName = f;
                });
            }
            else if (iconFiles.Count == 1)
            {
                fileName = iconFiles[0];
            }
            //Rea
            string uniqueIconFileName = String.Format("{0}{1}", appIdentifier, Path.GetExtension(fileName));

            ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(ipaFilePath));
            using (var filestream = new FileStream(ipaFilePath, FileMode.Open, FileAccess.Read))
            {
                ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                ICSharpCode.SharpZipLib.Zip.ZipEntry item;


                while ((item = zip.GetNextEntry()) != null)
                {
                    Match match = Regex.Match(item.Name.ToLower(), string.Format(@"Payload/([A-Za-z0-9\-.]+)\/{0}", fileName.ToLower()), RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                       
                        using (Stream strm = zipfile.GetInputStream(item))
                        {

                            //int size = strm.Read(bytes, 0, bytes.Length);

                            //using (BinaryReader s = new BinaryReader(strm))
                            //{
                            //    byte[] bytes2 = new byte[size];
                            //    Array.Copy(bytes, bytes2, size);
                            //    using (MemoryStream input = new MemoryStream(bytes2))
                            //    {
                            //        using (FileStream output = File.Create(Path.Combine(iconDirectory, uniqueIconFileName)))
                            //        {
                            //            try
                            //            {
                            //                PNGDecrush.PNGDecrusher.Decrush(strm, output);
                            //            }
                            //            catch (InvalidDataException ex)
                            //            {
                            //                //Continue, unable to resolve icon data
                            //            }
                            //        }

                            //    }
                            //}


                            byte[] ret = null;
                            ret = new byte[item.Size];
                            strm.Read(ret, 0, ret.Length);
                            using (MemoryStream input = new MemoryStream(ret))
                            {
                                using (FileStream output = File.Create(Path.Combine(iconDirectory, uniqueIconFileName)))
                                {
                                    try
                                    {
                                        PNGDecrush.PNGDecrusher.Decrush(input, output);
                                    }
                                    catch (InvalidDataException ex)
                                    {
                                        //Continue, unable to resolve icon data
                                    }
                                }
                            }

                            //using (MemoryStream input = new MemoryStream())
                            //{

                            //    using (FileStream output = File.Create(Path.Combine(iconDirectory, uniqueIconFileName)))
                            //    {
                            //        try
                            //        {
                            //            PNGDecrush.PNGDecrusher.Decrush(strm, output);
                            //        }
                            //        catch (InvalidDataException ex)
                            //        {
                            //            //Continue, unable to resolve icon data
                            //        }
                            //    }
                            //}
                          
                        }
                      

                        break;
                    }

                }

            }



        }
Example #55
0
 protected TZipArchive(ICSharpCode.SharpZipLib.Zip.ZipFile Zip)
 {
     this.zip = Zip;
 }
Example #56
0
 public ZipArchive(string ZipFile)
 {
     zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ZipFile);
 }
Example #57
0
        /// <summary>
        /// Constructs a new zip instance.
        /// If the file exists and has a non-zero length we read it,
        /// otherwise we create a new archive.
        /// Note that due to a bug with updating archives, an archive cannot be both read and write.
        /// </summary>
        /// <param name="file">The name of the file to read or write</param>
        /// <param name="options">The options passed on the commandline</param>
        public FileArchiveZip(string file, Dictionary<string, string> options)
        {
            if (!System.IO.File.Exists(file) || new System.IO.FileInfo(file).Length == 0)
            {
            #if SHARPZIPLIBWORKS
                m_zip = new FileArchiveZip(ICSharpCode.SharpZipLib.Zip.ZipFile.Create(filename));
                m_zip.BeginUpdate();
            #else
                m_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(file));
            #endif
                int compressionLevel = DEFAULT_COMPRESSION_LEVEL;
                int tmplvl;
                string cplvl = null;

                if (options.TryGetValue(COMPRESSION_LEVEL_OPTION, out cplvl) && int.TryParse(cplvl, out tmplvl))
                    compressionLevel = Math.Max(Math.Min(9, tmplvl), 0);

                m_stream.SetLevel(compressionLevel);
            }
            else
            {
                m_zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(file);
            }
        }
        //private static void CopyStream(Stream input, Stream output)
        //{
        //    byte[] buffer = new byte[8 * 1024];
        //    int len;
        //    while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        //    {
        //        output.Write(buffer, 0, len);
        //    }
        //}
        public static AndroidManifestData GetManifestData(String apkFilePath)
        {
            byte[] manifestData = null;
            byte[] resourcesData = null;
            using (ICSharpCode.SharpZipLib.Zip.ZipInputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipInputStream(File.OpenRead(apkFilePath)))
            {
                using (var filestream = new FileStream(apkFilePath, FileMode.Open, FileAccess.Read))
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipfile = new ICSharpCode.SharpZipLib.Zip.ZipFile(filestream);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry item;
                    while ((item = zip.GetNextEntry()) != null)
                    {
                        if (item.Name.ToLower() == "androidmanifest.xml")
                        {
                            manifestData = new byte[50 * 1024];
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                strm.Read(manifestData, 0, manifestData.Length);
                            }

                        }
                        if (item.Name.ToLower() == "resources.arsc")
                        {
                            using (Stream strm = zipfile.GetInputStream(item))
                            {
                                using (BinaryReader s = new BinaryReader(strm))
                                {
                                    resourcesData = s.ReadBytes((int)s.BaseStream.Length);

                                }
                            }
                        }
                    }
                }
            }

            Iteedee.ApkReader.ApkReader reader = new ApkReader.ApkReader();

            Iteedee.ApkReader.ApkInfo info = reader.extractInfo(manifestData, resourcesData);
            string AppName = info.label;


            return new AndroidManifestData()
            {
                VersionCode = info.versionCode,
                VersionName = info.versionName,
                PackageName = info.packageName,
                ApplicationName = info.label,
                ApplicationIconName = GetBestIconAvailable(info.iconFileNameToGet)

            };
            
        }
Example #59
0
        /// <summary>
        /// Unzip a local file and return its contents via streamreader to a local the same location as the ZIP.
        /// </summary>
        /// <param name="zipFile">Location of the zip on the HD</param>
        /// <returns>List of unzipped file names</returns>
        public static List<string> UnzipToFolder(string zipFile)
        {
            //1. Initialize:
            var files = new List<string>();
            var slash = zipFile.LastIndexOf(Path.DirectorySeparatorChar);
            var outFolder = "";
            if (slash > 0)
            {
                outFolder = zipFile.Substring(0, slash);
            }
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;

            try
            {
                var fs = File.OpenRead(zipFile);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

                foreach (ZipEntry zipEntry in zf)
                {
                    //Ignore Directories
                    if (!zipEntry.IsFile) continue;

                    //Remove the folder from the entry
                    var entryFileName = Path.GetFileName(zipEntry.Name);
                    if (entryFileName == null) continue;

                    var buffer = new byte[4096];     // 4K is optimum
                    var zipStream = zf.GetInputStream(zipEntry);

                    // Manipulate the output filename here as desired.
                    var fullZipToPath = Path.Combine(outFolder, entryFileName);

                    //Save the file name for later:
                    files.Add(fullZipToPath);
                    //Log.Trace("Data.UnzipToFolder(): Input File: " + zipFile + ", Output Directory: " + fullZipToPath);

                    //Copy the data in buffer chunks
                    using (var streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
            return files;
        }
        public void PackagePublisherPackageFolderMustRespectHierarchy()
        {
            const string ProjectName1 = "PackageTest03";

            string IntegrationFolder = System.IO.Path.Combine("scenarioTests", ProjectName1);
            string CCNetConfigFile = System.IO.Path.Combine("IntegrationScenarios", "PackagePublisherTest03.xml");
            string ProjectStateFile = new System.IO.FileInfo(ProjectName1 + ".state").FullName;

            IntegrationCompleted = new System.Collections.Generic.Dictionary<string, bool>();

            string workingDirectory = "Packaging03";

            string infoFolder = string.Format("{0}{1}some{1}directories{1}deeper{1}_PublishedWebsites{1}MyProject{1}", workingDirectory, System.IO.Path.DirectorySeparatorChar);
            string subInfoFolder = string.Format("{0}{1}AFolder{1}", infoFolder, System.IO.Path.DirectorySeparatorChar);
            string f1 = string.Format("{0}{1}a.txt", infoFolder, System.IO.Path.DirectorySeparatorChar);
            string f2 = string.Format("{0}{1}b.txt", subInfoFolder, System.IO.Path.DirectorySeparatorChar);


            var ios = new CCNet.Core.Util.IoService();
            ios.DeleteIncludingReadOnlyObjects(infoFolder);
            ios.DeleteIncludingReadOnlyObjects("TheMegaWebSite");


            System.IO.Directory.CreateDirectory(infoFolder);
            System.IO.Directory.CreateDirectory(subInfoFolder);


            System.IO.File.WriteAllText(f1, "somedata");
            System.IO.File.WriteAllText(f2, "somedata");

            IntegrationCompleted.Add(ProjectName1, false);

            Log("Clear existing state file, to simulate first run : " + ProjectStateFile);
            System.IO.File.Delete(ProjectStateFile);

            Log("Clear integration folder to simulate first run");
            if (System.IO.Directory.Exists(IntegrationFolder)) System.IO.Directory.Delete(IntegrationFolder, true);


            CCNet.Remote.Messages.ProjectStatusResponse psr;
            CCNet.Remote.Messages.ProjectRequest pr1 = new CCNet.Remote.Messages.ProjectRequest(null, ProjectName1);


            Log("Making CruiseServerFactory");
            CCNet.Core.CruiseServerFactory csf = new CCNet.Core.CruiseServerFactory();

            Log("Making cruiseServer with config from :" + CCNetConfigFile);
            using (var cruiseServer = csf.Create(true, CCNetConfigFile))
            {

                // subscribe to integration complete to be able to wait for completion of a build
                cruiseServer.IntegrationCompleted += new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("Starting cruiseServer");
                cruiseServer.Start();

                System.Threading.Thread.Sleep(250); // give time to start

                Log("Forcing build");
                CheckResponse(cruiseServer.ForceBuild(pr1));

                System.Threading.Thread.Sleep(250); // give time to start the build

                Log("Waiting for integration to complete");
                while (!IntegrationCompleted[ProjectName1])
                {
                    for (int i = 1; i <= 4; i++) System.Threading.Thread.Sleep(250);
                    Log(" waiting ...");
                }

                // un-subscribe to integration complete 
                cruiseServer.IntegrationCompleted -= new EventHandler<ThoughtWorks.CruiseControl.Remote.Events.IntegrationCompletedEventArgs>(CruiseServerIntegrationCompleted);

                Log("getting project status");
                psr = cruiseServer.GetProjectStatus(pr1);
                CheckResponse(psr);

                Log("Stopping cruiseServer");
                cruiseServer.Stop();

                Log("waiting for cruiseServer to stop");
                cruiseServer.WaitForExit(pr1);
                Log("cruiseServer stopped");

            }

            Log("Checking the data");
            string ExpectedZipFile = string.Format("{0}{1}Artifacts{1}1{1}Project-package.zip", ProjectName1, System.IO.Path.DirectorySeparatorChar);
            Assert.IsTrue(System.IO.File.Exists(ExpectedZipFile), "zip package not found at expected location");

            ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(ExpectedZipFile);
            string expectedFiles = string.Empty;

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf)
            {
                System.Diagnostics.Debug.WriteLine(ze.Name);
                expectedFiles += ze.Name;
            }

            Assert.AreEqual(@"MegaWebSite/AFolder/b.txtMegaWebSite/a.txt", expectedFiles);
        }