Exemplo n.º 1
0
    public string GetInformationFromFile(string fullPath, string defaultValue)
    {
        if (RuntimePlatform.Android == Application.platform)
        {
            string fileName = Path.GetFileName(fullPath);
            using (MemoryStream m = new MemoryStream())
            {
                string             obbfile = Application.dataPath;
                Ionic.Zip.ZipFile  zipfile = new Ionic.Zip.ZipFile(obbfile);
                Ionic.Zip.ZipEntry ze      = zipfile["assets/" + fileName];
                if (ze != null)
                {
                    ze.Extract(m);
                    m.Seek(0, SeekOrigin.Begin);
                    using (StreamReader s = new StreamReader(m))
                    {
                        string fileText = s.ReadLine();
                        return(fileText);
                    }
                }
            }
        }
        else
        {
            if (File.Exists(fullPath))
            {
                String fileText = File.ReadAllText(fullPath);
                return(fileText);
            }
        }

        return(defaultValue);
    }
Exemplo n.º 2
0
 private bool AreEqual(ZipEntry approvedEntry, ZipEntry receivedEntry)
 {
     if (approvedEntry.IsDirectory && receivedEntry.IsDirectory)
     {
         return true;
     }
     using (var approvedStream = new MemoryStream())
     {
         using (var receivedStream = new MemoryStream())
         {
             approvedEntry.Extract(approvedStream);
             receivedEntry.Extract(receivedStream);
             var approvedBytes = approvedStream.ToArray();
             var receivedBytes = receivedStream.ToArray();
             var areEqual = approvedBytes == receivedBytes;
             for (int i = 0; i < receivedBytes.Length && i < approvedBytes.Length; i++)
             {
                 if (receivedBytes[i] != approvedBytes[i])
                 {
                     Logger.Event("Failed on {0}[{1}]      '{2}' != '{3}'", receivedEntry.FileName, i,
                         (char) receivedBytes[i], (char) approvedBytes[i]);
                     return false;
                 }
             }
             return true;
         }
     }
 }
Exemplo n.º 3
0
        public MemoryStream GetEntryMemoryStream(ZipEntry zipEntry)
        {
            var stream = new MemoryStream();
            zipEntry.Extract(stream);
            stream.Position = 0;

            return stream;
        }
 private static Bitmap LoadBitmap(ZipEntry zipEntry)
 {
     MemoryStream stream = new MemoryStream();
     zipEntry.Extract(stream);
     stream.Position = 0;
     Bitmap result = new Bitmap(stream);
     stream.Dispose();
     return result;
 }
        public static string ExtractFileFromStream(ZipEntry entry)
        {
            var reader = new MemoryStream();
            entry.Extract(reader);
            reader = new MemoryStream(reader.ToArray());

            var streamReader = new StreamReader(reader);

            var text = streamReader.ReadToEnd();
            reader.Dispose();
            return text;
        }
 public static MemoryStream ExtractFileToStream(string zipSource, string filePath)
 {
     MemoryStream stream = new MemoryStream();
     using (ZipFile zip = ZipFile.Read(zipSource))
     {
         var matchFile = new ZipEntry();
         foreach (var file in zip.Where(file => file.FileName == filePath))
             matchFile = file;
         matchFile.Extract(stream);
     }
     return stream;
 }
Exemplo n.º 7
0
        private BitmapSource GenerateBitmapFromZipEntry(ZipEntry entry)
        {
            MemoryStream stream = new MemoryStream();
            entry.Extract(stream);
            stream.Seek(0, SeekOrigin.Begin);

            var decoder = BitmapDecoder.Create(stream,
                BitmapCreateOptions.None,
                BitmapCacheOption.OnLoad);
            BitmapSource bitmapSource = decoder.Frames[0];

            stream.Dispose();

            return bitmapSource;
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            string regularplist, path, ipaname;

            
            //App Name
            Console.WriteLine("Please read the first Readme.md/n");
            Console.WriteLine("Please \"XXXX\" in the place of complete Payload/XXXX.app");
            ipaname = Console.ReadLine() + ".app";

            //App Path
            Console.WriteLine("Enter the path ipa");
            path = Console.ReadLine();

            ZipEntry entry = new ZipEntry();
            using (ZipFile zip = ZipFile.Read(path))
            {
                entry = zip["Payload\\" + ipaname +"\\Info.plist"];
            }
            
            using (MemoryStream stream = new MemoryStream())
            {
                entry.Extract(stream);
                stream.Position = 0;
                var downPlist = Plist.readPlist(stream, plistType.Auto);
                regularplist = Plist.writeXml(downPlist);
            }

            var parsedPlist = XDocument.Parse(regularplist);

            String[] requiredKeys = new String[] { "DTCompiler", "CFBundleIdentifier", "CFBundleShortVersionString", "MinimumOSVersion", "CFBundleSupportedPlatforms"};
            var filtredXmlData = parsedPlist.Root.Element("dict").Elements("key").Where(p => requiredKeys.Contains(p.Value)).Select(p => new
            {
                key = p.Value,
                value = Regex.Replace(p.NextNode.ToString(), "<.*?>", string.Empty)
            }).ToDictionary(k => k.key, v => v.value);

            Console.WriteLine(filtredXmlData["DTCompiler"]);
            Console.WriteLine(filtredXmlData["CFBundleIdentifier"]);
            Console.WriteLine(filtredXmlData["CFBundleShortVersionString"]);
            Console.WriteLine(filtredXmlData["CFBundleSupportedPlatforms"]);
            Console.Read();
        }
Exemplo n.º 9
0
    private static int GetFileFormatByZip(Ionic.Zip.ZipFile oZipFile)
    {
        if (oZipFile.ContainsEntry("[Content_Types].xml"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["[Content_Types].xml"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.UTF8Encoding.UTF8.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.document.macroEnabled.main+xml") ||
                    -1 != sContent.IndexOf("application/vnd.ms-word.template.macroEnabledTemplate.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.sheet.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-excel.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLSX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.template.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.slideshow.macroEnabled.main+xml") ||
                         -1 != sContent.IndexOf("application/vnd.ms-powerpoint.template.macroEnabled.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPTX);
                }
                else if (-1 != sContent.IndexOf("application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_PPSX);
                }
            }
        }
        if (oZipFile.ContainsEntry("mimetype"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["mimetype"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.text"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_ODT);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.spreadsheet"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_SPREADSHEET_ODS);
                }
                else if (-1 != sContent.IndexOf("application/vnd.oasis.opendocument.presentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_PRESENTATION_ODP);
                }
                else if (-1 != sContent.IndexOf("application/epub+zip"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_DOCUMENT_EPUB);
                }
            }
        }
        if (oZipFile.ContainsEntry("_rels/.rels"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["_rels/.rels"];
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                string sContent = System.Text.ASCIIEncoding.ASCII.GetString(oMemoryStream.GetBuffer(), 0, (int)oMemoryStream.Length);
                if (-1 != sContent.IndexOf("http://schemas.microsoft.com/xps/2005/06/fixedrepresentation"))
                {
                    return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
                }
            }
        }

        if (oZipFile.ContainsEntry("_rels/.rels/[0].piece"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_XPS);
        }
        if (oZipFile.ContainsEntry("Editor.bin"))
        {
            Ionic.Zip.ZipEntry oEntry = oZipFile["Editor.bin"];
            int nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN;
            using (MemoryStream oMemoryStream = new MemoryStream((int)oEntry.UncompressedSize))
            {
                oEntry.Extract(oMemoryStream);
                oMemoryStream.Position = 0;
                int nSignatureLength = 4;
                if (oMemoryStream.Length >= nSignatureLength)
                {
                    byte[] aSignature = new byte[nSignatureLength];
                    oMemoryStream.Read(aSignature, 0, nSignatureLength);
                    string sSignature = System.Text.ASCIIEncoding.ASCII.GetString(aSignature);
                    switch (sSignature)
                    {
                    case "DOCY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_DOCY; break;

                    case "XLSY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_XLSY; break;

                    case "PPTY": nFormat = FileFormats.AVS_OFFICESTUDIO_FILE_TEAMLAB_PPTY; break;
                    }
                }
            }
            if (FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN != nFormat)
            {
                return(nFormat);
            }
        }
        else if (oZipFile.ContainsEntry("Editor.xml"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_PRESENTATION);
        }
        else if (oZipFile.ContainsEntry("Editor.svg"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DRAWING);
        }
        else if (oZipFile.ContainsEntry("Editor.html.arch"))
        {
            return(FileFormats.AVS_OFFICESTUDIO_FILE_OTHER_OLD_DOCUMENT);
        }
        return(FileFormats.AVS_OFFICESTUDIO_FILE_UNKNOWN);
    }
Exemplo n.º 10
0
        // return:
        //      0   一样
        //      1   不一样
        static int CompareEntry(ZipEntry e1, ZipEntry e2)
        {
            // 解压缩看看是否内容一样
            using (Stream stream1 = new MemoryStream())
            using (Stream stream2 = new MemoryStream())
            {
                e1.Extract(stream1);
                e2.Extract(stream2);
                if (stream1.Length != stream2.Length)
                    return 1;

                // 准备从流中读出
                stream1.Position = 0;
                stream2.Position = 0;
                while (true)
                {
                    int nRet = stream1.ReadByte();
                    if (nRet == -1)
                        return 0;
                    if (nRet != stream2.ReadByte())
                        return 1;
                }
            }
        }
Exemplo n.º 11
0
 private void ParseModuleStream()
 {
     _moduleConfigEntry = ParseZipFile(_zip, out _moduleDirName);
     if (_moduleConfigEntry!=null)
     {
         using (MemoryStream ms = new MemoryStream())
         {
             _moduleConfigEntry.Extract(ms);
             ms.Position = 0;
             _moduleInfo = ModuleInfo.Get(ms);
         }
         if (!string.IsNullOrEmpty(_moduleInfo.ModuleName))
         {
             _moduleName = _moduleInfo.ModuleName;
         }
         else
         {
             _moduleInfo.ModuleName = _moduleName;
         }
     }
 }
Exemplo n.º 12
0
        static void ParsePassJson(PassKit p, ZipEntry e, Dictionary<string, string> discoveredHashes)
        {
            JObject json = null;

            try
            {
                using (var ms = new MemoryStream())
                {
                    e.Extract(ms);

                    ms.Position = 0;

                    var sha1 = CalculateSHA1(ms.GetBuffer(), Encoding.UTF8);
                    if (!discoveredHashes.ContainsKey(e.FileName.ToLower()))
                        discoveredHashes.Add(e.FileName.ToLower(), sha1);

                    using (var sr = new StreamReader(ms))
                        json = JObject.Parse(sr.ReadToEnd());
                }
            }
            catch { }

            if (json["passTypeIdentifier"] == null)
                throw new MissingFieldException("PassKit must include a passTypeIdentifier field!");

            if (json["formatVersion"] == null)
                throw new MissingFieldException("PassKit must include a formatVersion field!");

            if (json["organizationName"] == null)
                throw new MissingFieldException("PassKit must include a organizationName field!");

            if (json["serialNumber"] == null)
                throw new MissingFieldException("PassKit must include a serialNumber field!");

            if (json["teamIdentifier"] == null)
                throw new MissingFieldException("PassKit must include a teamIdentifier field!");

            if (json["description"] == null)
                throw new MissingFieldException("PassKit must include a description field!");

            p.PassTypeIdentifier = json["passTypeIdentifier"].Value<string>();
            p.FormatVersion = json["formatVersion"].Value<int>();
            p.OrganizationName = json["organizationName"].Value<string>();
            p.SerialNumber = json["serialNumber"].Value<string>();
            p.TeamIdentifier = json["teamIdentifier"].Value<string>();
            p.Description = json["description"].Value<string>();

            if (json["webServiceURL"] != null)
                p.WebServiceURL = json["webServiceURL"].ToString();

            if (json["authenticationToken"] != null)
                p.AuthenticationToken = json["authenticationToken"].ToString();

            if (json["suppressStripShine"] != null)
                p.SuppressStripShine = json["suppressStripShine"].Value<bool>();

            if (json["foregroundColor"] != null)
                p.ForegroundColor = PKColor.Parse(json["foregroundColor"].ToString());

            if (json["backgroundColor"] != null)
                p.BackgroundColor = PKColor.Parse(json["backgroundColor"].ToString());

            if (json["labelColor"] != null)
                p.LabelColor = PKColor.Parse(json["labelColor"].ToString());

            if (json["logoText"] != null)
                p.LogoText = json["logoText"].Value<string>();

            if (json["relevantDate"] != null)
                p.RelevantDate = json["relevantDate"].Value<DateTime>();

            if (json["associatedStoreIdentifiers"] != null)
            {
                if (p.AssociatedStoreIdentifiers == null)
                    p.AssociatedStoreIdentifiers = new List<string>();

                var idarr = (JArray)json["associatedStoreIdentifiers"];
                foreach (var ida in idarr)
                    p.AssociatedStoreIdentifiers.Add(ida.ToString());
            }

            if (json["locations"] != null && json["locations"] is JArray)
            {
                foreach (JObject loc in (JArray)json["locations"])
                {
                    var pkl = new PKLocation();

                    if (loc["latitude"] == null)
                        throw new MissingFieldException("PassKit Location must include a latitude field!");

                    if (loc["longitude"] == null)
                        throw new MissingFieldException("PassKit Location must include a longitude field!");

                    pkl.Latitude = loc["latitude"].Value<double>();
                    pkl.Longitude = loc["longitude"].Value<double>();

                    if (loc["altitude"] != null)
                        pkl.Altitude = loc["altitude"].Value<double>();

                    if (loc["relevantText"] != null)
                        pkl.RelevantText = loc["relevantText"].Value<string>();

                    if (p.Locations == null)
                        p.Locations = new PKLocationList();

                    p.Locations.Add(pkl);
                }
            }

            if (json["barcode"] != null)
            {
                var bc = json["barcode"] as JObject;

                if (p.Barcode == null)
                    p.Barcode = new PKBarcode();

                if (bc["message"] == null)
                    throw new MissingFieldException("PassKit Barcode must include a message field!");

                if (bc["format"] == null)
                    throw new MissingFieldException("PassKit Barcode must include a format field!");

                if (bc["messageEncoding"] == null)
                    throw new MissingFieldException("PassKit Barcode must include a messageEncoding field!");

                if (bc["altText"] != null)
                    p.Barcode.AltText = bc["altText"].ToString();

                p.Barcode.Message = bc["message"].ToString();
                p.Barcode.MessageEncoding = bc["messageEncoding"].ToString();
                p.Barcode.Format = (PKBarcodeFormat)Enum.Parse(typeof(PKBarcodeFormat), bc["format"].ToString());
            }

            if (json["eventTicket"] != null)
            {
                p.PassType = PKPassType.EventTicket;
                ParsePassSet(p, json["eventTicket"] as JObject);
            }

            if (json["boardingPass"] != null)
            {
                p.PassType = PKPassType.BoardingPass;
                ParsePassSet(p, json["boardingPass"] as JObject);
            }

            if (json["coupon"] != null)
            {
                p.PassType = PKPassType.Coupon;
                ParsePassSet(p, json["coupon"] as JObject);
            }

            if (json["generic"] != null)
            {
                p.PassType = PKPassType.Generic;
                ParsePassSet(p, json["generic"] as JObject);
            }

            if (json["storeCard"] != null)
            {
                p.PassType = PKPassType.StoreCard;
                ParsePassSet(p, json["storeCard"] as JObject);
            }
        }
Exemplo n.º 13
0
        static void ParseManifest(PassKit p, ZipEntry e, Dictionary<string, string> discoveredHashes)
        {
            JObject json = null;

            try
            {
                using (var ms = new MemoryStream())
                {
                    e.Extract(ms);

                    using (var sr = new StreamReader(ms))
                    {
                        ms.Position = 0;

                        var sha1 = CalculateSHA1(ms.GetBuffer(), Encoding.UTF8);
                        if (!discoveredHashes.ContainsKey(e.FileName.ToLower()))
                            discoveredHashes.Add(e.FileName.ToLower(), sha1);

                        var sj = sr.ReadToEnd();

                        json = JObject.Parse(sj);
                    }
                }
            }
            catch { }

            foreach (var prop in json.Properties())
            {
                var val = prop.Value.ToString();
                var name = prop.Name.ToLower();

                if (!p.Manifest.ContainsKey(name))
                    p.Manifest.Add(name, val);
                else
                    p.Manifest[name] = val;
            }
        }
Exemplo n.º 14
0
        private void ParseReportData(ZipEntry report)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                report.Extract(ms);
                ms.Position = 0;

                SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
                ExcelFile file = ExcelFile.Load(ms, LoadOptions.XlsDefault);
                var date = DateTime.Parse(report.FileName.Substring(0, 11));

                this.ParseExcelSheets(report.FileName, file, date);
            }
        }
Exemplo n.º 15
0
        private static void ProcessRemoveList(ZipEntry file)
        {
            MemoryStream ms = new MemoryStream();
            file.Extract(ms);

            ms.Seek(0, SeekOrigin.Begin);

            StreamReader reader = new StreamReader(ms);

            string line = "";

            while ((line = reader.ReadLine()) != null)
            {
                if (string.IsNullOrEmpty(line))
                    continue;

                line = line.Replace("\\", "/");

                string folderPath = "";
                string fileSuffix = "";
                string zipPath = "";

                if (line.Contains("levels/"))
                    fileSuffix = "/";
                else
                    fileSuffix = "_";

                // We're removing a (top) folder
                if (!_zipRegex.IsMatch(line))
                {
                    folderPath = line;

                    // Make sure we're not deleting the root mod folder
                    if (folderPath.Length <= 0)
                        continue;

                    // Try removing folder from the list, if it's been previously added by an update.
                    try
                    {

                        _zipLists.Remove(new ZipInfo(folderPath, fileSuffix + "server.zip"));
                        _zipLists.Remove(new ZipInfo(folderPath, fileSuffix + "client.zip"));
                        Console.WriteLine("Removed {0} from zip list", folderPath);
                    }
                    catch (IndexOutOfRangeException ex)
                    {
                        Console.WriteLine(" NOTICE: {0}", ex.Message);
                    }

                    // Try removing folder/file from mod, if it's already in there.
                    try
                    {
                        string path = Path.Combine(_mod.ParentPath, folderPath.Replace("/", "\\"));

                        FileAttributes attr = File.GetAttributes(path);

                        if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            Directory.Delete(path, true);
                        }
                        else
                        {
                            File.Delete(path);
                        }

                        Console.WriteLine("Removed {0} from mod", folderPath);
                    }
                    catch (DirectoryNotFoundException ex)
                    {
                        Console.WriteLine(" NOTICE: {0}", ex.Message);
                    }
                    catch (FileNotFoundException ex)
                    {
                        Console.WriteLine(" NOTICE: {0}", ex.Message);
                    }

                    continue;
                }
                else
                {
                    Match match = _zipRegex.Match(line);

                    folderPath = match.Groups[1].Captures[0].Value.ToLower();
                    zipPath = match.Groups[2].Captures[0].Value.ToLower();

                    // If it's a directory we need to delete it from both server and client files
                    // TODO: Better way than checking for dot? What if filename has dot? (this.object.con)
                    if (!zipPath.Contains("."))
                    {
                        AddZipCall(new ZipInfo(folderPath, fileSuffix + "server.zip"), zipPath, CallType.Remove);
                        AddZipCall(new ZipInfo(folderPath, fileSuffix + "client.zip"), zipPath, CallType.Remove);

                        continue;
                    }

                    if (_serverRegex.IsMatch(zipPath))
                    {
                        AddZipCall(new ZipInfo(folderPath, fileSuffix + "server.zip"), zipPath, CallType.Remove);
                    }
                    else
                    {
                        AddZipCall(new ZipInfo(folderPath, fileSuffix + "client.zip"), zipPath, CallType.Remove);
                    }
                }
            }
        }
Exemplo n.º 16
0
 private Assembly ExtractAssembly(ZipEntry entry)
 {
     var stream = new MemoryStream();
     entry.Extract(stream);
     return Assembly.Load(stream.ReadAllBytes());
 }
Exemplo n.º 17
0
        private byte[] ExtractResource(ZipEntry entry)
        {
            // ZipEntry.Extract will throw an exception if the ZipFile has been
            // modified. Check the VersionNeeded - if it's zero then the entry
            // needs to be saved before we can extract it.
            if (entry.VersionNeeded == 0)
            {
                this.ResetZip(true);
                entry = _zip[entry.FileName];
            }

            using (var stream = new MemoryStream())
            {
                entry.Extract(stream);
                return stream.ToArray();
            }
        }
Exemplo n.º 18
0
            public WaitHandle AsycDecompress(ZipEntry srcEntry)
            {
                if (Data == null) {
                    if (StreamPool.Capacity < srcEntry.UncompressedSize) StreamPool.Capacity = (int)srcEntry.UncompressedSize;
                    this.Data = StreamPool.Allocate();

                    // Extract
                    if (srcEntry.CompressionMethod == CompressionMethod.Deflate && srcEntry.Encryption == EncryptionAlgorithm.None) {
                        PropertyInfo dataPosProp = typeof(ZipEntry).GetProperty("FileDataPosition", BindingFlags.NonPublic | BindingFlags.Instance);
                        long dataPos = (long)dataPosProp.GetValue(srcEntry, new object[] { });
                        PropertyInfo streamProp = typeof(ZipEntry).GetProperty("ArchiveStream", BindingFlags.NonPublic | BindingFlags.Instance);
                        Stream stream = (Stream)streamProp.GetValue(srcEntry, new object[] { });
                        MemoryStream compressedData = StreamPool.Allocate();
                        compressedData.SetLength(srcEntry.CompressedSize);
                        stream.Seek(dataPos, SeekOrigin.Begin);

                        Stopwatch watch = new Stopwatch();
                        watch.Start();
                        stream.Read(compressedData.GetBuffer(), 0, (int)compressedData.Length);
                        watch.Stop();
                        TotalReadTime += watch.Elapsed;
                        TotalReadSizeMB += (double)compressedData.Length / 1024 / 1024;

                        DeflateStream decompressStream = new System.IO.Compression.DeflateStream(compressedData, CompressionMode.Decompress, true);
                        this.LoadDone = new ManualResetEvent(false);

                        Interlocked.Increment(ref activeDecompressionThreads);
                        ThreadPool.QueueUserWorkItem(delegate {
                            byte[] buffer = new byte[64 * 1024];
                            int readCount;
                            while ((readCount = decompressStream.Read(buffer, 0, buffer.Length)) != 0) {
                                this.Data.Write(buffer, 0, readCount);
                            }
                            decompressStream.Close();
                            StreamPool.Release(ref compressedData);
                            Interlocked.Decrement(ref activeDecompressionThreads);
                            this.LoadDone.Set();
                        });
                    } else {
                        srcEntry.Extract(this.Data);
                        this.LoadDone = new ManualResetEvent(true);
                    }
                }
                return this.LoadDone;
            }
Exemplo n.º 19
0
        /// <summary>
        /// Metoda, ki se pokliče, ko kliknemo na gumb Razširi. Odpre saveFileDialog in prebere kam bomo datoteko
        /// shranili.
        /// OPOMBA: metoda še ne deluje 100% pravilno.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExtract_Click(object sender, EventArgs e)
        {
            filesList = new StringCollection();

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fileExplorer.SelectedItems.Count > 0 && fbd.ShowDialog() == DialogResult.OK)
            {
                // Pridobi shranjevalno pot
                string savePath = fbd.SelectedPath;

                foreach (ListViewItem item in fileExplorer.SelectedItems)
                {
                    string file = item.SubItems[0].Text;

                    // Preveri katera oblika datoteke je: ZIP, TAR, GZIP ali TAR.BZ2
                    if (Path.GetExtension(txtPath.Text) == ".zip")
                    {
                        ZipFile  zip   = Ionic.Zip.ZipFile.Read(txtPath.Text);
                        ZipEntry entry = zip[file];
                        if (zip[file].UsesEncryption == true)
                        {
                            PasswordPrompt passWin = new PasswordPrompt();
                            passWin.ShowDialog();

                            zip.Password = passWin.pass;
                            try
                            {
                                entry.ExtractWithPassword(savePath, passWin.pass);
                            }
                            catch (BadPasswordException)
                            {
                                if (MessageBox.Show("Napačno geslo", "Napaka", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Retry)
                                {
                                    passWin.ShowDialog();
                                }
                            }
                        }

                        string enExists = savePath + @"\" + entry.FileName;

                        if (File.Exists(enExists))
                        {
                            if (MessageBox.Show("Datoteka " + file + " že obstaja. Ali jo želite zamenjati?", "Datoteka obstaja", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                            {
                                entry.Extract(savePath, ExtractExistingFileAction.OverwriteSilently);
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            entry.Extract(savePath);
                        }
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".tar")
                    {
                        byte[]         outBuffer = new byte[4096];
                        TarInputStream tar       = new TarInputStream(new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read));
                        TarEntry       curEntry  = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                FileStream   fs = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".bz2")
                    {
                        Stream           str      = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read);
                        BZip2InputStream bzStr    = new BZip2InputStream(str);
                        TarInputStream   tar      = new TarInputStream(bzStr);
                        TarEntry         curEntry = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                byte[]       outBuffer = new byte[curEntry.Size];
                                FileStream   fs        = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw        = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }

                    else if (Path.GetExtension(txtPath.Text) == ".tgz")
                    {
                        Stream          str   = new FileStream(txtPath.Text, FileMode.Open, FileAccess.Read);
                        GZipInputStream gzStr = new GZipInputStream(str);
                        TarInputStream  tar   = new TarInputStream(gzStr);

                        TarEntry curEntry = tar.GetNextEntry();
                        while (curEntry != null)
                        {
                            if (curEntry.Name == file)
                            {
                                byte[]       outBuffer = new byte[curEntry.Size];
                                FileStream   fs        = new FileStream(savePath + @"\" + curEntry.Name, FileMode.Create, FileAccess.Write);
                                BinaryWriter bw        = new BinaryWriter(fs);
                                tar.Read(outBuffer, 0, (int)curEntry.Size);
                                bw.Write(outBuffer, 0, outBuffer.Length);
                                bw.Close();
                            }
                            curEntry = tar.GetNextEntry();
                        }
                        tar.Close();
                    }
                }
            }
            else
            {
                MessageBox.Show("Nobena datoteka ni bila izbrana. Prosimo izberite datoteke.", "Napaka", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemplo n.º 20
0
 private string GetString(ZipEntry entry)
 {
     MemoryStream buffer = new MemoryStream();
     entry.Extract(buffer);
     buffer.Position = 0;
     StreamReader reader = new StreamReader(buffer);
     string s = reader.ReadToEnd();
     buffer.Position = 0;
     reader.Close();
     return s;
 }
Exemplo n.º 21
0
        void ExtractFile(ZipEntry e, string strTargetDir)
        {
#if NO
            string strTempDir = Path.Combine(this.UserDir, "temp");
            PathUtil.CreateDirIfNeed(strTempDir);
#endif
            string strTempDir = this.TempDir;

            string strTempPath = Path.Combine(strTempDir, Path.GetFileName(e.FileName));
            string strTargetPath = Path.Combine(strTargetDir, e.FileName);

            using (FileStream stream = new FileStream(strTempPath, FileMode.Create))
            {
                e.Extract(stream);
            }

            int nErrorCount = 0;
            for (; ; )
            {
                try
                {
                    // 确保目标目录已经创建
                    PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strTargetPath));

                    File.Copy(strTempPath, strTargetPath, true);
                }
                catch (Exception ex)
                {
                    if (nErrorCount > 10)
                    {
                        DialogResult result = MessageBox.Show(this,
"复制文件 " + strTempPath + " 到 " + strTargetPath + " 的过程中出现错误: " + ex.Message + "。\r\n\r\n是否要重试?",
"dp2Installer",
MessageBoxButtons.RetryCancel,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
                        if (result == System.Windows.Forms.DialogResult.Cancel)
                        {
                            throw new Exception("复制文件 " + strTargetPath + " 到 " + strTargetPath + " 的过程中出现错误: " + ex.Message);
                        }
                        nErrorCount = 0;
                    }

                    nErrorCount++;
                    Thread.Sleep(1000);
                    continue;
                }
                break;
            }
            File.Delete(strTempPath);
        }
Exemplo n.º 22
0
        static byte[] ReadStream(ZipEntry e, Dictionary<string, string> discoveredHashes)
        {
            using (var input = new MemoryStream())
            {
                e.Extract(input);

                input.Position = 0;

                byte[] total_stream = new byte[0];

                byte[] stream_array = new byte[0];
                // Setup whatever read size you want (small here for testing)
                byte[] buffer = new byte[32];// * 1024];
                int read = 0;

                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream_array = new byte[total_stream.Length + read];
                    total_stream.CopyTo(stream_array, 0);
                    Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
                    total_stream = stream_array;
                }

                var sha1 = CalculateSHA1(total_stream, Encoding.UTF8);

                if (!discoveredHashes.ContainsKey(e.FileName.ToLower()))
                    discoveredHashes.Add(e.FileName.ToLower(), sha1);

                return total_stream;
            }
        }
Exemplo n.º 23
0
        private void ExtractResourceToStream(ZipEntry entry, Stream stream)
        {
            // ZipEntry.Extract will throw an exception if the ZipFile has been
            // modified. Check the VersionNeeded - if it's zero then the entry
            // needs to be saved before we can extract it.
            if (entry.VersionNeeded == 0)
            {
                this.ResetZip(true);
                entry = _zip[entry.FileName];
            }

            entry.Extract(stream);
        }
Exemplo n.º 24
0
        internal bool extract(ZipEntry entry, out Guid gameGuid, Guid testGuid)
        {
            try
            {
                Log.InfoFormat("Extracting {0},{1}", entry.FileName, testGuid);
                bool ret = false;
                gameGuid = testGuid;
                string[] split = entry.FileName.Split('/');
                Log.InfoFormat("Split file name {0},{1}", entry.FileName, testGuid);
                if (split.Length == 5)
                {
                    Log.InfoFormat("File name right count {0},{1}", entry.FileName, testGuid);
                    O8cEntry o8cEntry = new O8cEntry()
                                            {
                                                gameGuid = split[0],
                                                setsDir = split[1],
                                                setGuid = split[2],
                                                cardsDir = split[3],
                                                cardImage = split[4]
                                            };
                    Log.InfoFormat("Checking if testGuid is empty {0},{1}", entry.FileName, testGuid);
                    if (testGuid.Equals(Guid.Empty))
                    {
                        Log.InfoFormat("testGuid is empty {0},{1}", entry.FileName, testGuid);
                        testGuid = Guid.Parse(o8cEntry.gameGuid);
                        gameGuid = Guid.Parse(o8cEntry.gameGuid);
                        Log.InfoFormat("Setting gameguid and testguid {0},{1},{2}", entry.FileName, testGuid, gameGuid);
                    }
                    Log.InfoFormat("Checking if {0}=={1} {2}", testGuid, o8cEntry.gameGuid, entry.FileName);
                    if (!testGuid.Equals(Guid.Parse(o8cEntry.gameGuid)))
                    {
                        Log.InfoFormat("{0}!={1} {2}", testGuid, o8cEntry.gameGuid, entry.FileName);
                        return (ret);
                    }
                    Log.InfoFormat("Checking if should extract part {0},{1}", entry.FileName, testGuid);
                    if (ShouldExtract(o8cEntry))
                    {
                        Log.InfoFormat(
                            "Should extract, so extracting {0},{1},{2}",
                            Paths.Get().ImageDatabasePath,
                            entry.FileName,
                            testGuid);
                        entry.Extract(Paths.Get().ImageDatabasePath, ExtractExistingFileAction.OverwriteSilently);
                        Log.InfoFormat("Extracted {0},{1},{2}", Paths.Get().ImageDatabasePath, entry.FileName, testGuid);
                        ret = true;
                    }
                }
                Log.InfoFormat("Finishing {0},{1},{2}", ret, entry.FileName, testGuid);
                return (ret);

            }
            catch (IOException e)
            {
                throw new UserMessageException("Error extracting {0} to {1}\n{2}", entry.FileName, Paths.Get().DatabasePath, e.Message);
            }
            finally
            {
                Log.InfoFormat("Finished {0},{1}", entry.FileName, testGuid);
            }
        }
        private void _SaveSfxStub(string exeToGenerate, SelfExtractorSaveOptions options)
        {
            string nameOfIconFile      = null;
            string stubExe             = null;
            string unpackedResourceDir = null;
            string tmpDir = null;

            try
            {
                if (File.Exists(exeToGenerate))
                {
                    if (Verbose)
                    {
                        StatusMessageTextWriter.WriteLine("The existing file ({0}) will be overwritten.", exeToGenerate);
                    }
                }
                if (!exeToGenerate.EndsWith(".exe"))
                {
                    if (Verbose)
                    {
                        StatusMessageTextWriter.WriteLine("Warning: The generated self-extracting file will not have an .exe extension.");
                    }
                }

                // workitem 10553
                tmpDir  = TempFileFolder ?? Path.GetDirectoryName(exeToGenerate);
                stubExe = GenerateTempPathname(tmpDir, "exe");

                // get the Ionic.Zip assembly
                Assembly a1 = typeof(ZipFile).Assembly;

                using (var csharp = new Microsoft.CSharp.CSharpCodeProvider
                                        (new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v2.0" }
                })) {
                    // The following is a perfect opportunity for a linq query, but
                    // I cannot use it.  DotNetZip needs to run on .NET 2.0,
                    // and using LINQ would break that. Here's what it would look
                    // like:
                    //
                    //   var settings = (from x in SettingsList
                    //                   where x.Flavor == flavor
                    //                   select x).First();

                    ExtractorSettings settings = null;
                    foreach (var x in SettingsList)
                    {
                        if (x.Flavor == options.Flavor)
                        {
                            settings = x;
                            break;
                        }
                    }

                    // sanity check; should never happen
                    if (settings == null)
                    {
                        throw new BadStateException(String.Format("While saving a Self-Extracting Zip, Cannot find that flavor ({0})?", options.Flavor));
                    }

                    // This is the list of referenced assemblies.  Ionic.Zip is
                    // needed here.  Also if it is the winforms (gui) extractor, we
                    // need other referenced assemblies, like
                    // System.Windows.Forms.dll, etc.
                    var cp = new System.CodeDom.Compiler.CompilerParameters();
                    cp.ReferencedAssemblies.Add(a1.Location);
                    if (settings.ReferencedAssemblies != null)
                    {
                        foreach (string ra in settings.ReferencedAssemblies)
                        {
                            cp.ReferencedAssemblies.Add(ra);
                        }
                    }

                    cp.GenerateInMemory        = false;
                    cp.GenerateExecutable      = true;
                    cp.IncludeDebugInformation = false;
                    cp.CompilerOptions         = "";

                    Assembly a2 = Assembly.GetExecutingAssembly();

                    // Use this to concatenate all the source code resources into a
                    // single module.
                    var sb = new System.Text.StringBuilder();

                    // In case there are compiler errors later, we allocate a source
                    // file name now. If errors are detected, we'll spool the source
                    // code as well as the errors (in comments) into that filename,
                    // and throw an exception with the filename.  Makes it easier to
                    // diagnose.  This should be rare; most errors happen only
                    // during devlpmt of DotNetZip itself, but there are rare
                    // occasions when they occur in other cases.
                    string sourceFile = GenerateTempPathname(tmpDir, "cs");


                    // // debugging: enumerate the resources in this assembly
                    // Console.WriteLine("Resources in this assembly:");
                    // foreach (string rsrc in a2.GetManifestResourceNames())
                    //   {
                    //     Console.WriteLine(rsrc);
                    //   }
                    // Console.WriteLine();


                    // all the source code is embedded in the DLL as a zip file.
                    using (ZipFile zip = ZipFile.Read(a2.GetManifestResourceStream("Ionic.Zip.Resources.ZippedResources.zip")))
                    {
                        // // debugging: enumerate the files in the embedded zip
                        // Console.WriteLine("Entries in the embbedded zip:");
                        // foreach (ZipEntry entry in zip)
                        //   {
                        //     Console.WriteLine(entry.FileName);
                        //   }
                        // Console.WriteLine();

                        unpackedResourceDir = GenerateTempPathname(tmpDir, "tmp");

                        if (String.IsNullOrEmpty(options.IconFile))
                        {
                            // Use the ico file that is embedded into the Ionic.Zip
                            // DLL itself.  To do this we must unpack the icon to
                            // the filesystem, in order to specify it on the cmdline
                            // of csc.exe.  This method will remove the unpacked
                            // file later.
                            System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            ZipEntry e = zip["zippedFile.ico"];
                            // Must not extract a readonly file - it will be impossible to
                            // delete later.
                            if ((e.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                            {
                                e.Attributes ^= FileAttributes.ReadOnly;
                            }
                            e.Extract(unpackedResourceDir);
                            nameOfIconFile      = Path.Combine(unpackedResourceDir, "zippedFile.ico");
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", nameOfIconFile);
                        }
                        else
                        {
                            cp.CompilerOptions += String.Format("/win32icon:\"{0}\"", options.IconFile);
                        }

                        cp.OutputAssembly = stubExe;

                        if (options.Flavor == SelfExtractorFlavor.WinFormsApplication)
                        {
                            cp.CompilerOptions += " /target:winexe";
                        }

                        if (!String.IsNullOrEmpty(options.AdditionalCompilerSwitches))
                        {
                            cp.CompilerOptions += " " + options.AdditionalCompilerSwitches;
                        }

                        if (String.IsNullOrEmpty(cp.CompilerOptions))
                        {
                            cp.CompilerOptions = null;
                        }

                        if ((settings.CopyThroughResources != null) && (settings.CopyThroughResources.Count != 0))
                        {
                            if (!Directory.Exists(unpackedResourceDir))
                            {
                                System.IO.Directory.CreateDirectory(unpackedResourceDir);
                            }
                            foreach (string re in settings.CopyThroughResources)
                            {
                                string filename = Path.Combine(unpackedResourceDir, re);

                                ExtractResourceToFile(a2, re, filename);
                                // add the file into the target assembly as an embedded resource
                                cp.EmbeddedResources.Add(filename);
                            }
                        }

                        // add the Ionic.Utils.Zip DLL as an embedded resource
                        cp.EmbeddedResources.Add(a1.Location);

                        // file header
                        sb.Append("// " + Path.GetFileName(sourceFile) + "\n")
                        .Append("// --------------------------------------------\n//\n")
                        .Append("// This SFX source file was generated by DotNetZip ")
                        .Append(ZipFile.LibraryVersion.ToString())
                        .Append("\n//         at ")
                        .Append(System.DateTime.Now.ToString("yyyy MMMM dd  HH:mm:ss"))
                        .Append("\n//\n// --------------------------------------------\n\n\n");

                        // assembly attributes
                        if (!String.IsNullOrEmpty(options.Description))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\""
                                      + options.Description.Replace("\"", "")
                                      + "\")]\n");
                        }
                        else
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyTitle(\"DotNetZip SFX Archive\")]\n");
                        }

                        if (!String.IsNullOrEmpty(options.ProductVersion))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyInformationalVersion(\""
                                      + options.ProductVersion.Replace("\"", "")
                                      + "\")]\n");
                        }

                        // workitem
                        string copyright =
                            (String.IsNullOrEmpty(options.Copyright))
                            ? "Extractor: Copyright © Dino Chiesa 2008-2011"
                            : options.Copyright.Replace("\"", "");

                        if (!String.IsNullOrEmpty(options.ProductName))
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"")
                            .Append(options.ProductName.Replace("\"", ""))
                            .Append("\")]\n");
                        }
                        else
                        {
                            sb.Append("[assembly: System.Reflection.AssemblyProduct(\"DotNetZip\")]\n");
                        }


                        sb.Append("[assembly: System.Reflection.AssemblyCopyright(\"" + copyright + "\")]\n")
                        .Append(String.Format("[assembly: System.Reflection.AssemblyVersion(\"{0}\")]\n", ZipFile.LibraryVersion.ToString()));
                        if (options.FileVersion != null)
                        {
                            sb.Append(String.Format("[assembly: System.Reflection.AssemblyFileVersion(\"{0}\")]\n",
                                                    options.FileVersion.ToString()));
                        }

                        sb.Append("\n\n\n");

                        // Set the default extract location if it is available
                        string extractLoc = options.DefaultExtractDirectory;
                        if (extractLoc != null)
                        {
                            // remove double-quotes and replace slash with double-slash.
                            // This, because the value is going to be embedded into a
                            // cs file as a quoted string, and it needs to be escaped.
                            extractLoc = extractLoc.Replace("\"", "").Replace("\\", "\\\\");
                        }

                        string postExCmdLine = options.PostExtractCommandLine;
                        if (postExCmdLine != null)
                        {
                            postExCmdLine = postExCmdLine.Replace("\\", "\\\\");
                            postExCmdLine = postExCmdLine.Replace("\"", "\\\"");
                        }


                        foreach (string rc in settings.ResourcesToCompile)
                        {
                            using (Stream s = zip[rc].OpenReader())
                            {
                                if (s == null)
                                {
                                    throw new ZipException(String.Format("missing resource '{0}'", rc));
                                }
                                using (StreamReader sr = new StreamReader(s))
                                {
                                    while (sr.Peek() >= 0)
                                    {
                                        string line = sr.ReadLine();
                                        if (extractLoc != null)
                                        {
                                            line = line.Replace("@@EXTRACTLOCATION", extractLoc);
                                        }

                                        line = line.Replace("@@REMOVE_AFTER_EXECUTE", options.RemoveUnpackedFilesAfterExecute.ToString());
                                        line = line.Replace("@@QUIET", options.Quiet.ToString());
                                        if (!String.IsNullOrEmpty(options.SfxExeWindowTitle))
                                        {
                                            line = line.Replace("@@SFX_EXE_WINDOW_TITLE", options.SfxExeWindowTitle);
                                        }

                                        line = line.Replace("@@EXTRACT_EXISTING_FILE", ((int)options.ExtractExistingFile).ToString());

                                        if (postExCmdLine != null)
                                        {
                                            line = line.Replace("@@POST_UNPACK_CMD_LINE", postExCmdLine);
                                        }

                                        sb.Append(line).Append("\n");
                                    }
                                }
                                sb.Append("\n\n");
                            }
                        }
                    }

                    string LiteralSource = sb.ToString();

#if DEBUGSFX
                    // for debugging only
                    string sourceModule = GenerateTempPathname(tmpDir, "cs");
                    using (StreamWriter sw = File.CreateText(sourceModule))
                    {
                        sw.Write(LiteralSource);
                    }
                    Console.WriteLine("source: {0}", sourceModule);
#endif

                    var cr = csharp.CompileAssemblyFromSource(cp, LiteralSource);


                    if (cr == null)
                    {
                        throw new SfxGenerationException("Cannot compile the extraction logic!");
                    }

                    if (Verbose)
                    {
                        foreach (string output in cr.Output)
                        {
                            StatusMessageTextWriter.WriteLine(output);
                        }
                    }

                    if (cr.Errors.Count != 0)
                    {
                        using (var sourceFileStream = new FileStream(sourceFile, FileMode.Create))
                            using (TextWriter tw = new StreamWriter(sourceFileStream))
                            {
                                // first, the source we compiled
                                tw.Write(LiteralSource);

                                // now, append the compile errors
                                tw.Write("\n\n\n// ------------------------------------------------------------------\n");
                                tw.Write("// Errors during compilation: \n//\n");
                                string p = Path.GetFileName(sourceFile);

                                foreach (System.CodeDom.Compiler.CompilerError error in cr.Errors)
                                {
                                    tw.Write(String.Format("//   {0}({1},{2}): {3} {4}: {5}\n//\n",
                                                           p,                                     // 0
                                                           error.Line,                            // 1
                                                           error.Column,                          // 2
                                                           error.IsWarning ? "Warning" : "error", // 3
                                                           error.ErrorNumber,                     // 4
                                                           error.ErrorText));                     // 5
                                }
                            }
                        throw new SfxGenerationException(String.Format("Errors compiling the extraction logic!  {0}", sourceFile));
                    }

                    OnSaveEvent(ZipProgressEventType.Saving_AfterCompileSelfExtractor);

                    // Now, copy the resulting EXE image to the _writestream.
                    // Because this stub exe is being saved first, the effect will be to
                    // concatenate the exe and the zip data together.
                    using (System.IO.Stream input = System.IO.File.OpenRead(stubExe))
                    {
                        byte[] buffer = new byte[4000];
                        int    n      = 1;
                        while (n != 0)
                        {
                            n = input.Read(buffer, 0, buffer.Length);
                            if (n != 0)
                            {
                                WriteStream.Write(buffer, 0, n);
                            }
                        }
                    }
                }

                OnSaveEvent(ZipProgressEventType.Saving_AfterSaveTempArchive);
            }
            finally
            {
                try
                {
                    if (Directory.Exists(unpackedResourceDir))
                    {
                        try { Directory.Delete(unpackedResourceDir, true); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                    if (File.Exists(stubExe))
                    {
                        try { File.Delete(stubExe); }
                        catch (System.IO.IOException exc1)
                        {
                            StatusMessageTextWriter.WriteLine("Warning: Exception: {0}", exc1);
                        }
                    }
                }
                catch (System.IO.IOException) { }
            }

            return;
        }
Exemplo n.º 26
0
        public void xap(string path)
        {
            ZipEntry entry = new ZipEntry();
            using (ZipFile zip = ZipFile.Read(path))
            {
                entry = zip["WMAppManifest.xml"];
            }

            using (MemoryStream stream = new MemoryStream())
            {
                entry.Extract(stream);
                stream.Position = 0;
                var serializer = new XmlSerializer(typeof(Deployment));
                var deployment = serializer.Deserialize(new NamespaceIgnorantXmlTextReader(stream)) as Deployment;
                System.Console.WriteLine(deployment.App.Version);
                System.Console.WriteLine(deployment.App.Description);
                System.Console.WriteLine(deployment.App.Capabilities);
                System.Console.Read();
            }

        }
Exemplo n.º 27
-1
        private String ReadLastModified(ZipEntry entry)
        {
            if (entry == null)
            {
                return ProblemData.NO_PROBLEM_DATA_VERSION;
            }

            using (MemoryStream ms = new MemoryStream())
            {
                entry.Extract(ms);
                ms.Seek(0, SeekOrigin.Begin);

                StreamReader reader = new StreamReader(ms, Encoding.UTF8);
                String lastModified = reader.ReadToEnd();

                reader.Close();
                reader.Dispose();

                ms.Close();

                return lastModified;
            }
        }