FindEntry() public method

Return the index of the entry with a matching name
/// The Zip file has been closed. ///
public FindEntry ( string name, bool ignoreCase ) : int
name string Entry name to find
ignoreCase bool If true the comparison is case insensitive
return int
Exemplo n.º 1
0
        private List <string> reLoadModList()
        {
            modlistBox.Items.Clear();
            var modlist = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + "mods").ToList();

            foreach (var item in modlist)
            {
                ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(item);

                var enrty = zip.FindEntry("config.json", true);
                if (enrty >= 0)
                {
                    var            config  = MODConfigHelper.LoadConfig(zip.GetInputStream(enrty));
                    ModItemControl boxitem = new ModItemControl();
                    boxitem.ItemName = config.Name;
                    //boxitem.IsRed = true;
                    // ListBoxItem boxitem = new ListBoxItem();
                    // boxitem.Content = config.Name;
                    boxitem.Tag         = config;
                    boxitem.DataContext = item;
                    modlistBox.Items.Add(boxitem);
                }
            }

            return(modlist);
        }
Exemplo n.º 2
0
 public static void LoadShareString(string file)
 {
     if (ShareString.file == file)
         return;
     ZipFile myZip = new ZipFile(file);
     int index = myZip.FindEntry("xl/sharedStrings.xml", true);
     Stream ss = myZip.GetInputStream(index);
     XmlReader myReader = XmlReader.Create(ss);
     string content = string.Empty;
     bool inEntry = false;
     bool inContent = false;
     int postion = 0;
     while (myReader.Read())
     {
         switch (myReader.NodeType)
         {
             case XmlNodeType.Element:
                 if (myReader.Name == "sst")
                 {
                     int count = Convert.ToInt32(myReader.GetAttribute("uniqueCount"));
                     shareWords = new string[count];
                 }
                 else if (myReader.Name == "si")
                 {
                     inEntry = true;
                 }
                 else if (myReader.Name == "t" && inEntry)
                 {
                     inContent = true;
                 }
                 break;
             case XmlNodeType.Text:
                 if (inContent)
                 {
                     content += myReader.Value;
                 }
                 break;
             case XmlNodeType.EndElement:
                 if (myReader.Name == "si")
                 {
                     inEntry = false;
                     shareWords[postion++] = content;
                     content = string.Empty;
                 }
                 else if (myReader.Name == "t")
                 {
                     inContent = false;
                 }
                 break;
         }
     }
     myReader.Close();
     ss.Dispose();
 }
        /// <summary>
        /// 获取sheet表单内容。
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public SheetData GetSheetData(int index)
        {
            if (ShareString.shareWords == null)
            {
                ShareString.LoadShareString(filePath);
            }
            ZipFile myZip = new ZipFile(filePath);
            int num = myZip.FindEntry(mySheetList[index].path, true);
            Stream ss = myZip.GetInputStream(num);
            SheetData mySheetData = new SheetData(ss);

            return mySheetData;
        }
Exemplo n.º 4
0
		private void AssertDoesNotContainFile(string partialPath)
		{
			ZipFile f = null;
			try
			{
				f = new ZipFile(_destinationZip);
				Assert.AreEqual(-1, f.FindEntry(GetZipFileInternalPath(partialPath), true));
			}
			finally
			{
				if (f != null)
				{
					f.Close();
				}
			}
		}
Exemplo n.º 5
0
 public byte[] GetContentRaw(string loc)
 {
     byte[] cont = null;
     ZipFile zipFile = new ZipFile(FileLoc);
     int i = zipFile.FindEntry(loc, false);
     if (i >= 0)
     {
         ZipEntry ze = zipFile[i];
         Stream s = zipFile.GetInputStream(ze);
         byte[] buff = new byte[(int)ze.Size];
         s.Read(buff, 0, buff.Length);
         cont = buff;
     }
     zipFile.Close();
     return cont;
 }
Exemplo n.º 6
0
 public byte[] GetContentRaw(string loc)
 {
     byte[] cont = null;
     ZipFile zipFile = new ZipFile(this.zipArchive);
     int i = zipFile.FindEntry(loc, false);
     if (i >= 0)
     {
         ZipEntry ze = zipFile[i];
         Stream s = zipFile.GetInputStream(ze);
         byte[] buff = new byte[(int)ze.Size];
         s.Read(buff, 0, buff.Length);
         cont = buff;
     }
     zipFile.IsStreamOwner = false; zipFile.Close();
     this.zipArchive.Position = 0;
     return cont;
 }
Exemplo n.º 7
0
 public Bitmap ReadDDSFile(string pakFile, string internalFile)
 {
     string key = pakFile + "!" + internalFile;
     Debug.Assert(internalFile.EndsWith("dds"));
     if (!imageCache.ContainsKey(key)) {
         var itempak = OpenPAKFile(Path.Combine(aionPath, pakFile));
         using (ZipFile zFile = new ZipFile(itempak)) {
             int entrynum = zFile.FindEntry(internalFile, true);
             if (entrynum == -1) { return null; }
             var entry = zFile[entrynum];
             var iconFile = zFile.GetInputStream(entry);
             byte[] bytes = new byte[entry.Size];
             iconFile.Read(bytes, 0, bytes.Length);
             Bitmap b = JitConverter.DDSDataToBMP(bytes);
             imageCache[key] = b;
         }
     }
     return imageCache[key];
 }
Exemplo n.º 8
0
		/// <summary>
		/// Copies assembly files from package to Bin folder
		/// </summary>
		public static void InstallAssemblyPackage(List<UpdateFileInfo> updateFiles, ZipFile zipPackage)
		{
			// Bin path!
			string extenderPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Bin");

			foreach (UpdateFileInfo fileInfo in updateFiles)
			{
				if (IsPackageFileForbidden(fileInfo.FilePath))
					continue;

				// the file path
				string installPath = Path.Combine(extenderPath, fileInfo.FilePath);

				// Ignore existence
				if (fileInfo.IgnoreExistence && File.Exists(installPath))
					continue;

				// find file in zip package
				int index = zipPackage.FindEntry(fileInfo.FilePath, true);

				if (index == -1)
					throw new InvalidDataException("Package files are invalid");

				// Ignore specifed version
				int compare = 1;
				if (!string.IsNullOrEmpty(fileInfo.IgnoreASProxyVersion))
					compare = Common.CompareASProxyVersions(Consts.General.ASProxyVersion, fileInfo.IgnoreASProxyVersion);

				// Only check if they are not equal
				if (compare != 0)
				{
					// Installable, do it!
					using (Stream zipStream = zipPackage.GetInputStream(index))
					using (FileStream file = new FileStream(installPath, FileMode.Create, FileAccess.Write, FileShare.None))
					{
						ReadWriteStream(zipStream, file);
					}
				}
			}
		}
Exemplo n.º 9
0
        public void ZipFileFind()
        {
            string tempFile = null;

            try
            {
                tempFile = Path.GetTempPath();
            }
            catch (SecurityException)
            {
            }

            Assertion.AssertNotNull("No permission to execute this test?", tempFile);

            if (tempFile != null)
            {
                tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
                MakeZipFile(tempFile, new String[] { "Farriera", "Champagne", "Urban myth" }, 10, "Aha");

                ZipFile zipFile = new ZipFile(tempFile);
                Assertion.AssertEquals("Expected 1 entry", 3, zipFile.Size);

                int testIndex = zipFile.FindEntry("Farriera", false);
                Assertion.AssertEquals("Case sensitive find failure", 0, testIndex);
                Assertion.Assert(string.Compare(zipFile[testIndex].Name, "Farriera", false) == 0);

                testIndex = zipFile.FindEntry("Farriera", true);
                Assertion.AssertEquals("Case insensitive find failure", 0, testIndex);
                Assertion.Assert(string.Compare(zipFile[testIndex].Name, "Farriera", true) == 0);

                testIndex = zipFile.FindEntry("urban mYTH", false);
                Assertion.AssertEquals("Case sensitive find failure", -1, testIndex);

                testIndex = zipFile.FindEntry("urban mYTH", true);
                Assertion.AssertEquals("Case insensitive find failure", 2, testIndex);
                Assertion.Assert(string.Compare(zipFile[testIndex].Name, "urban mYTH", true) == 0);

                testIndex = zipFile.FindEntry("Champane.", false);
                Assertion.AssertEquals("Case sensitive find failure", -1, testIndex);

                testIndex = zipFile.FindEntry("Champane.", true);
                Assertion.AssertEquals("Case insensitive find failure", -1, testIndex);

                zipFile.Close();
                File.Delete(tempFile);
            }
        }
Exemplo n.º 10
0
        private string ReadModInfo()
        {
            using (var stream = this.File.OpenRead())
            {
                using (var zip = new ZipFile(stream))
                {
                    int index = zip.FindEntry(Constants.MCModInfoFile, true);
                    if (index == -1)
                    {
                        Diagnostic.Error("Could not find {0} in {1}", Constants.MCModInfoFile, this.File);
                        return null;
                    }

                    using (var entryStream = zip.GetInputStream(index))
                    {
                        using (var reader = new StreamReader(entryStream))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Получение иконки APK-приложения
        /// </summary>
        /// <param name="filename">Путь до приложения</param>
        /// <returns>Икорка</returns>
        public static ImageSource GetApkIcon(string filename)
        {
            //Нужно создавать новые экземпляры, ибо BeginOutputReadLine() блухает
            Environment.aaptProc.StartInfo.Arguments = "dump badging \"" + filename + "\"";
            ProcessStartInfo pStartInfo = Environment.aaptProc.StartInfo;
            Environment.aaptProc = new Process();
            Environment.aaptProc.StartInfo = pStartInfo;

            StringBuilder output = new StringBuilder();
            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            {
                Environment.aaptProc.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                        outputWaitHandle.Set();
                    else
                        output.AppendLine(e.Data);
                };

                Environment.aaptProc.Start();
                Environment.aaptProc.BeginOutputReadLine();
                if (Environment.aaptProc.WaitForExit(1000) && outputWaitHandle.WaitOne(1000))
                {
                    Regex regex = new Regex(@"^application:\slabel='(.*)'\sicon='(.*)'$");
                    string IconPath = string.Empty;
                    foreach (string line in output.ToString().Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (regex.IsMatch(line))
                            IconPath = regex.Match(line).Groups[2].Value;
                    }
                    if (!string.IsNullOrEmpty(IconPath))
                    {
                        ZipFile zip = new ZipFile(filename);
                        BitmapImage bitmap = new BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = zip.GetInputStream(zip.FindEntry(IconPath, true));
                        bitmap.EndInit();
                        bitmap.Freeze();
                        zip.Close();
                        return bitmap;
                    }
                }
            }
            return null;
        }
Exemplo n.º 12
0
        private void formSettings_Load(object sender, EventArgs e)
        {
            // Set installation path textbox
            textInstallPath.Text = Properties.Settings.Default.InstallPath;
            checkConflicts.Checked = SettingsManager.DisableConflictCheck;
            checkEnableSound.Checked = Properties.Settings.Default.EnableSound;
            listThemes.SelectedIndex = 0;

            if(Directory.Exists("Themes"))
            {
                foreach(string file in Directory.GetFiles("Themes", "*.sbtheme"))
                {
                    // Read theme names
                    ZipFile themeZip = new ZipFile(file);
                    var themeEntry = themeZip.FindEntry("Theme.xml", true);
                    if(themeEntry >= 0)
                    {
                        var themeStream = themeZip.GetInputStream(themeZip[themeEntry]);
                        using (StreamReader themeReader = new StreamReader(themeStream))
                        {
                            XmlSerializer themeSerializer = new XmlSerializer(typeof(ThemeXml.Theme));
                            var theme = (ThemeXml.Theme)themeSerializer.Deserialize(themeReader);
                            listThemes.Items.Add(theme.Name);
                            themeFiles.Add(file);
                            if (Properties.Settings.Default.ThemeFile == file) listThemes.SelectedIndex = themeFiles.Count-1;
                        }
                    }
                }
            } else
            {
                tabControl.TabPages.RemoveAt(1);
            }
        }
Exemplo n.º 13
0
        private void InstallDictionary(ZipFile zipFile)
        {
            string installed = null;

            foreach (ZipEntry entry in zipFile)
            {
                if (entry.Name.EndsWith(".dic"))
                {
                    string path;
                    string code;

                    int pos = entry.Name.LastIndexOf('/');

                    if (pos == -1)
                    {
                        path = null;
                        code = entry.Name;
                    }
                    else
                    {
                        path = entry.Name.Substring(0, pos + 1);
                        code = entry.Name.Substring(pos + 1);
                    }

                    code = code.Substring(0, code.Length - 4);

                    try
                    {
                        CultureInfo.GetCultureInfo(code);
                    }
                    catch (CultureNotFoundException)
                    {
                        continue;
                    }

                    int affEntryIndex = zipFile.FindEntry(
                        path + code + ".aff",
                        true
                    );

                    if (affEntryIndex == -1)
                    {
                        continue;
                    }

                    using (var source = zipFile.GetInputStream(entry))
                    {
                        SaveFile(source, code + ".dic");
                    }

                    using (var source = zipFile.GetInputStream(affEntryIndex))
                    {
                        SaveFile(source, code + ".aff");
                    }

                    // Install the first found, if there are multiple present.

                    if (installed == null)
                        installed = code;
                }
            }

            if (installed != null)
            {
                using (var key = Program.BaseKey)
                {
                    key.SetValue("Spell Check Language", installed);
                }

                LoadDictionary();
            }

            return;
        }
Exemplo n.º 14
0
        void SetContent(string loc, byte[] content)
        {
            ZipFile zipFile = new ZipFile(FileLoc);

            // Must call BeginUpdate to start, and CommitUpdate at the end.
            zipFile.BeginUpdate();
            if (loc.Contains('/'))
            {
                int i = loc.IndexOf('/');
                string dir = loc.Remove(i + 1, loc.Length - i - 1);
                if (zipFile.FindEntry(dir, true) < 0)
                {
                    zipFile.AddDirectory(dir);
                }
            }
            CustomStaticDataSource sds = new CustomStaticDataSource();
            using (MemoryStream ms = new MemoryStream(content))
            {
                sds.SetStream(ms);

                // If an entry of the same name already exists, it will be overwritten; otherwise added.
                zipFile.Add(sds, loc);

                // Both CommitUpdate and Close must be called.
                zipFile.CommitUpdate();
                zipFile.Close();
            }
        }
Exemplo n.º 15
0
        public void SetupTheme()
        {
            // Load theme
            if (File.Exists(Properties.Settings.Default.ThemeFile))
            {
                // attempt to load data from theme file
                try
                {
                    ZipFile themeFile = new ZipFile(Properties.Settings.Default.ThemeFile);
                    var themeEntry = themeFile.FindEntry("Theme.xml", true);
                    if (themeEntry >= 0)
                    {
                        var themeStream = themeFile.GetInputStream(themeFile[themeEntry]);
                        using (StreamReader themeReader = new StreamReader(themeStream))
                        {
                            XmlSerializer themeSerializer = new XmlSerializer(typeof(ThemeXml.Theme));
                            var theme = (ThemeXml.Theme)themeSerializer.Deserialize(themeReader);
                            baseColour = Color.FromArgb(theme.BaseColour.alpha, theme.BaseColour.red, theme.BaseColour.green, theme.BaseColour.blue);
                            hoverColour = Color.FromArgb(theme.HoverColour.alpha, theme.HoverColour.red, theme.HoverColour.green, theme.HoverColour.blue);
                            exitColour = Color.FromArgb(theme.ExitColour.alpha, theme.ExitColour.red, theme.ExitColour.green, theme.ExitColour.blue);
                        }
                    }
                    var bgEntry = themeFile.FindEntry("launcherbg.png", true);
                    if (bgEntry >= 0)
                    {
                        BackgroundImage = Image.FromStream(themeFile.GetInputStream(themeFile[bgEntry]));
                    }
                    // TODO: implemenmt theme sound effects
                    var soundMoveEntry = themeFile.FindEntry("ui_move.wav", true);
                    if(soundMoveEntry >= 0)
                    {
                        playerMove = new SoundPlayer(themeFile.GetInputStream(themeFile[soundMoveEntry]));
                    }
                    var soundSelectEntry = themeFile.FindEntry("ui_select.wav", true);
                    if (soundSelectEntry >= 0)
                    {
                        playerSelect = new SoundPlayer(themeFile.GetInputStream(themeFile[soundSelectEntry]));
                    }
                }
                catch
                {

                }
            } else
            {
                // Setup default theme
                BackgroundImage = Properties.Resources.LAUNCHERBG;
                baseColour = Color.White;
                hoverColour = Color.Red;
                exitColour = Color.DarkGray;
                playerMove = new SoundPlayer(Properties.Resources.ui_move);
                playerSelect = new SoundPlayer(Properties.Resources.ui_select);
            }

            buttonStartGame.ForeColor = baseColour;
            buttonMods.ForeColor = baseColour;
            buttonSettings.ForeColor = baseColour;
            buttonExit.ForeColor = baseColour;
            labelClose.ForeColor = exitColour;
            labelVersion.ForeColor = baseColour;
        }
Exemplo n.º 16
0
		private void AssertHasReasonableContents()
		{
			Assert.IsTrue(File.Exists(_destinationZip));
			ZipFile f = null;
			try
			{
				f = new ZipFile(_destinationZip);
				Assert.AreNotEqual(-1, f.FindEntry("PRETEND/PRETEND.lift", true));
			}
			finally
			{
				if (f != null)
				{
					f.Close();
				}
			}
		}
Exemplo n.º 17
0
        /// <summary>
        /// Returns true when the <paramref name="inputFile"/> is password protected
        /// </summary>
        /// <param name="inputFile">The OpenDocument format file</param>
        public bool OpenDocumentFormatIsPasswordProtected(string inputFile)
        {
            var zipFile = new ZipFile(inputFile);

            // Check if the file is password protected
            var manifestEntry = zipFile.FindEntry("META-INF/manifest.xml", true);
            if (manifestEntry != -1)
            {
                using (var manifestEntryStream = zipFile.GetInputStream(manifestEntry))
                using (var manifestEntryMemoryStream = new MemoryStream())
                {
                    manifestEntryStream.CopyTo(manifestEntryMemoryStream);
                    manifestEntryMemoryStream.Position = 0;
                    using (var streamReader = new StreamReader(manifestEntryMemoryStream))
                    {
                        var manifest = streamReader.ReadToEnd();
                        if (manifest.ToUpperInvariant().Contains("ENCRYPTION-DATA"))
                            return true;
                    }
                }
            }

            return false;
        }
Exemplo n.º 18
0
        /// <summary>
        /// Extracts all the embedded object from the OpenDocument <paramref name="inputFile"/> to the 
        /// <see cref="outputFolder"/> and returns the files with full path as a list of strings
        /// </summary>
        /// <param name="inputFile">The OpenDocument format file</param>
        /// <param name="outputFolder">The output folder</param>
        /// <returns>List with files or en empty list when there are nog embedded files</returns>
        /// <exception cref="OEFileIsPasswordProtected">Raised when the OpenDocument format file is password protected</exception>
        internal List<string> ExtractFromOpenDocumentFormat(string inputFile, string outputFolder)
        {
            var result = new List<string>();

            var zipFile = new ZipFile(inputFile);
  
            // Check if the file is password protected
            var manifestEntry = zipFile.FindEntry("META-INF/manifest.xml", true);
            if (manifestEntry != -1)
            {
                using (var manifestEntryStream = zipFile.GetInputStream(manifestEntry))
                using (var manifestEntryMemoryStream = new MemoryStream())
                {
                    manifestEntryStream.CopyTo(manifestEntryMemoryStream);
                    manifestEntryMemoryStream.Position = 0;
                    using (var streamReader = new StreamReader(manifestEntryMemoryStream))
                    {
                        var manifest = streamReader.ReadToEnd();
                        if (manifest.ToUpperInvariant().Contains("ENCRYPTION-DATA"))
                            throw new OEFileIsPasswordProtected("The file '" + Path.GetFileName(inputFile) +
                                                                "' is password protected");
                    }
                }
            }

            foreach (ZipEntry zipEntry in zipFile)
            {
                if (!zipEntry.IsFile) continue;
                if (zipEntry.IsCrypted)
                    throw new OEFileIsPasswordProtected("The file '" + Path.GetFileName(inputFile) +
                                                                "' is password protected");

                var name = zipEntry.Name.ToUpperInvariant();
                if (!name.StartsWith("OBJECT") || name.Contains("/"))
                    continue;

                string fileName = null;

                var objectReplacementFileIndex = zipFile.FindEntry("ObjectReplacements/" + name, true);
                if (objectReplacementFileIndex != -1)
                    fileName = Extraction.GetFileNameFromObjectReplacementFile(zipFile, objectReplacementFileIndex);
                
                using (var zipEntryStream = zipFile.GetInputStream(zipEntry))
                using (var zipEntryMemoryStream = new MemoryStream())
                {
                    zipEntryStream.CopyTo(zipEntryMemoryStream);

                    using (var compoundFile = new CompoundFile(zipEntryMemoryStream))
                        result.Add(Extraction.SaveFromStorageNode(compoundFile.RootStorage, outputFolder, fileName));
                }
            }

            return result;
        }
Exemplo n.º 19
0
        private List<string> reLoadModList()
        {
            modlistBox.Items.Clear();
            var modlist = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory + "mods").ToList();

            foreach (var item in modlist)
            {
                ICSharpCode.SharpZipLib.Zip.ZipFile zip = new ICSharpCode.SharpZipLib.Zip.ZipFile(item);

                var enrty = zip.FindEntry("config.json", true);
                if (enrty >= 0)
                {
                    var config = MODConfigHelper.LoadConfig(zip.GetInputStream(enrty));
                    ModItemControl boxitem = new ModItemControl();
                    boxitem.ItemName = config.Name;
                    //boxitem.IsRed = true;
                    // ListBoxItem boxitem = new ListBoxItem();
                    // boxitem.Content = config.Name;
                    boxitem.Tag = config;
                    boxitem.DataContext = item;
                    modlistBox.Items.Add(boxitem);
                }
            }

            return modlist;
        }
Exemplo n.º 20
0
        public void NameFactory()
        {
            MemoryStream memStream = new MemoryStream();
            DateTime fixedTime = new DateTime(1981, 4, 3);
            using (ZipFile f = new ZipFile(memStream))
            {
                f.IsStreamOwner = false;
                ((ZipEntryFactory)f.EntryFactory).IsUnicodeText = true;
                ((ZipEntryFactory)f.EntryFactory).Setting = ZipEntryFactory.TimeSetting.Fixed;
                ((ZipEntryFactory)f.EntryFactory).FixedDateTime = fixedTime;
                ((ZipEntryFactory)f.EntryFactory).SetAttributes = 1;
                f.BeginUpdate(new MemoryArchiveStorage());

                string[] names = new string[]
                {
                    "\u030A\u03B0",     // Greek
                    "\u0680\u0685",     // Arabic
                };

                foreach (string name in names)
                {
                    f.Add(new StringMemoryDataSource("Hello world"), name,
                          CompressionMethod.Deflated, true);
                }
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));

                foreach (string name in names)
                {
                    int index = f.FindEntry(name, true);

                    Assert.IsTrue(index >= 0);
                    ZipEntry found = f[index];
                    Assert.AreEqual(name, found.Name);
                    Assert.IsTrue(found.IsUnicodeText);
                    Assert.AreEqual(fixedTime, found.DateTime);
                    Assert.IsTrue(found.IsDOSEntry);
                }
            }
        }
Exemplo n.º 21
0
        public void Crypto_AddEncryptedEntryToExistingArchiveSafe()
        {
            MemoryStream ms = new MemoryStream();

            byte[] rawData;

            using (ZipFile testFile = new ZipFile(ms))
            {
                testFile.IsStreamOwner = false;
                testFile.BeginUpdate();
                testFile.Add(new StringMemoryDataSource("Aha"), "No1", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("And so it goes"), "No2", CompressionMethod.Stored);
                testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored);
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));
                rawData = ms.ToArray();
            }

            ms = new MemoryStream(rawData);

            using (ZipFile testFile = new ZipFile(ms))
            {
                Assert.IsTrue(testFile.TestArchive(true));

                testFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Safe));
                testFile.Password = "******";
                testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml");
                testFile.CommitUpdate();

                Assert.IsTrue(testFile.TestArchive(true));

                int entryIndex = testFile.FindEntry("encrypttest.xml", true);
                Assert.IsNotNull(entryIndex >= 0);
                Assert.IsTrue(testFile[entryIndex].IsCrypted);
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Process an incoming HTTP request
 /// </summary>
 /// <param name="context"></param>
 public void ProcessRequest(HttpContext context)
 {
     string mtype = GetMimeType(context.Request);
     context.Response.ContentType = mtype;
     FileInfo req = new FileInfo(context.Server.MapPath(context.Request.FilePath));
     if (req.Exists)
     {
         if (ManageModified(context, req)) { return; }
         context.Response.TransmitFile(context.Request.FilePath);
     }
     else
     {
         string rootDir = context.Server.MapPath("~");
         DirectoryInfo di = req.Directory;
         string name = req.Name;
         FileInfo[] zips;
         while (!di.Exists || (zips = di.GetFiles(name + ".zip")) == null || zips.Length == 0)
         {
             name = di.Name;
             di = di.Parent;
             if (di == null || !di.FullName.StartsWith(rootDir, StringComparison.OrdinalIgnoreCase))
             {
                 context.Response.StatusCode = 404;
                 context.Response.End();
                 return;
             }
         }
         if (ManageModified(context, zips[0])) { return; }
         using (ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(zips[0].FullName))
         {
             string fname = req.FullName.Substring(di.FullName.Length + name.Length + 2);
             int entryId = zf.FindEntry(fname, true);
             if (entryId < 0)
             {
                 fname = fname.Replace('\\', '/');
                 entryId = zf.FindEntry(fname, true);
             }
             if (entryId < 0)
             {
                 context.Response.StatusCode = 404;
                 context.Response.End();
                 return;
             }
             ZipEntry ze = zf[entryId];
             using (Stream s = zf.GetInputStream(entryId))
             {
                 using (BinaryReader br = new BinaryReader(s))
                 {
                     context.Response.BinaryWrite(br.ReadBytes((int)ze.Size));
                 }
             }
         }
     }
 }
Exemplo n.º 23
0
 private static byte[] GetZipEntry( ZipFile file, string entry, bool throwOnError )
 {
     if ( file.FindEntry( entry, false ) == -1 )
     {
         if ( throwOnError )
         {
             throw new FormatException( "entry not found" );
         }
         else
         {
             return null;
         }
     }
     else
     {
         ZipEntry zEntry = file.GetEntry( entry );
         Stream s = file.GetInputStream( zEntry );
         byte[] result = new byte[zEntry.Size];
         StreamUtils.ReadFully( s, result );
         return result;
     }
 }
Exemplo n.º 24
0
    public ExcelDocument(string filename)
    {
        if (!filename.Contains("\\"))
        {
            filename = FileService.GetPath() + "\\" + filename;
        }
        WorkSheets = new ObservableCollection <WorkSheet>();
        try
        {
            using (zip.ZipFile zf = new zip.ZipFile(filename))
            {
                IEnumerator ienum = zf.GetEnumerator();
                int         ifld  = zf.FindEntry("xl/workbook.xml", true);

                StreamReader srwb = new StreamReader(zf.GetInputStream(ifld));

                XmlDocument xd = new XmlDocument();
                xd.LoadXml(srwb.ReadToEnd());
                foreach (XmlNode xn in xd.DocumentElement.GetElementsByTagName("sheet"))
                {
                    string sheetId = xn.Attributes["sheetId"].Value;
                    string name    = xn.Attributes["name"].Value;
                    int    intsh   = zf.FindEntry("xl/worksheets/sheet" + sheetId + ".xml", true);
                    if (intsh != -1)
                    {
                        StreamReader sr = new StreamReader(zf.GetInputStream(intsh));
                        WorkSheet    ws = new WorkSheet()
                        {
                            SheetName = name, SheetXml = sr.ReadToEnd()
                        };

                        XmlDocument xdr = new XmlDocument();
                        xdr.LoadXml(ws.SheetXml);
                        string decsep    = (1.5).ToString();
                        string repdecsep = decsep.Contains(",") ? "," : decsep.Contains(".") ? "." : "";
                        decsep = decsep.Contains(",") ? "." : decsep.Contains(".") ? "," : "";

                        foreach (XmlNode xnr in xdr.DocumentElement.GetElementsByTagName("row"))
                        {
                            try
                            {
                                ExcelRow row = new ExcelRow();
                                row.Row  = int.Parse(xnr.Attributes["r"].Value.ToString());
                                row.Span = xnr.Attributes["spans"].Value;
                                foreach (XmlNode xnc in xnr.ChildNodes)
                                {
                                    try
                                    {
                                        ExcelCell cell = new ExcelCell();
                                        cell.Coord   = xnc.Attributes["r"].Value;
                                        cell.Formula = xnc.ChildNodes.Count > 0 && xnc.FirstChild != null && xnc.FirstChild.Name.Equals("f") ? xnc.FirstChild.InnerText : "";
                                        cell.Value   = xnc.ChildNodes.Count == 1 && xnc.FirstChild != null && xnc.FirstChild.Name.Equals("v") && !string.IsNullOrEmpty(xnc.FirstChild.InnerText) ? xnc.FirstChild.InnerText :
                                                       xnc.ChildNodes.Count > 1 && xnc.LastChild != null && xnc.LastChild.Name.Equals("v") && !string.IsNullOrEmpty(xnc.LastChild.InnerText) ? xnc.LastChild.InnerText : "0";
                                        row.Cells.Add(cell);
                                        row.setA2Z(cell.Coord);
                                    }
                                    catch (Exception ex) { string ss = ex.Message; }
                                }
                                ws.Rows.Add(row);
                            }
                            catch (Exception ex) { string ss = ex.Message; }
                        }

                        WorkSheets.Add(ws);
                    }
                }
            }
        }
        catch (Exception ex) { string ss = ex.Message; }
    }
Exemplo n.º 25
0
        public void FindEntry()
        {
            string tempFile = GetTempFilePath();
            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
            MakeZipFile(tempFile, new string[] { "Farriera", "Champagne", "Urban myth" }, 10, "Aha");

            using (ZipFile zipFile = new ZipFile(tempFile)) {
                Assert.AreEqual(3, zipFile.Count, "Expected 1 entry");

                int testIndex = zipFile.FindEntry("Farriera", false);
                Assert.AreEqual(0, testIndex, "Case sensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", false) == 0);

                testIndex = zipFile.FindEntry("Farriera", true);
                Assert.AreEqual(0, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", true) == 0);

                testIndex = zipFile.FindEntry("urban mYTH", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("urban mYTH", true);
                Assert.AreEqual(2, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "urban mYTH", true) == 0);

                testIndex = zipFile.FindEntry("Champane.", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("Champane.", true);
                Assert.AreEqual(-1, testIndex, "Case insensitive find failure");

                zipFile.Close();
            }
            File.Delete(tempFile);
        }
Exemplo n.º 26
0
 static byte[] Read(ZipFile zf, string entryName)
 {
     // search for entry name with forwardslash or backslash path seperators
     entryName = entryName.Replace("/", @"\");
     int entryIdx = zf.FindEntry(entryName, true);
     if (entryIdx == -1)
     {
         entryName = entryName.Replace(@"\", "/");
         entryIdx = zf.FindEntry(entryName, true);
     }
     // read bytes if entry found
     if (entryIdx != -1)
     {
         ZipEntry entry = zf[entryIdx];
         Stream s = zf.GetInputStream(entry);
         return new BinaryReader(s).ReadBytes((int)entry.Size);
     }
     else
         return null;
 }
Exemplo n.º 27
0
        public void UnicodeNames()
        {
            MemoryStream memStream = new MemoryStream();
            using (ZipFile f = new ZipFile(memStream))
            {
                f.IsStreamOwner = false;

                f.BeginUpdate(new MemoryArchiveStorage());

                string[] names = new string[]
                {
                    "\u030A\u03B0",     // Greek
                    "\u0680\u0685",     // Arabic
                };

                foreach (string name in names)
                {
                    f.Add(new StringMemoryDataSource("Hello world"), name,
                          CompressionMethod.Deflated, true);
                }
                f.CommitUpdate();
                Assert.IsTrue(f.TestArchive(true));

                foreach (string name in names)
                {
                    int index = f.FindEntry(name, true);

                    Assert.IsTrue(index >= 0);
                    ZipEntry found = f[index];
                    Assert.AreEqual(name, found.Name);
                }
            }
        }
        private void GenerateListing(
            DirectoryInfo thisSourceDirectoryInfo,
            SQLiteConnection theConnection,
            DirectoryInfo thisDirectoryInfo)
        {
            try
            {
                DirectoryInfo[] theSubDirectories =
                    thisDirectoryInfo.GetDirectories();

                Array.Sort(
                    theSubDirectories,
                    0,
                    theSubDirectories.Length,
                    new DirectorySort());

                foreach (DirectoryInfo thisSubDirectoryInfo in
                    theSubDirectories)
                {
                    this.GenerateListing(
                        thisSourceDirectoryInfo,
                        theConnection,
                        thisSubDirectoryInfo);
                }

                this._CurrentDirectoryInfo = thisDirectoryInfo;

                if (!thisDirectoryInfo.GetFiles("*.cdg").Length.Equals(0) ||
                    !thisDirectoryInfo.GetFiles("*.zip").Length.Equals(0))
                {
                    FileInfo[] theFiles =
                        thisDirectoryInfo.GetFiles();

                    Array.Sort(
                        theFiles,
                        0,
                        theFiles.Length,
                        new FileSort());

                    foreach (FileInfo thisFileInfo in theFiles)
                    {
                        this._CurrentFileInfo = thisFileInfo;

                        bool theArchiveContainsCDG = false;

                        if (thisFileInfo.Extension.Contains("zip"))
                        {
                            using (ZipFile theArchive = new ZipFile(thisFileInfo.FullName))
                            {
                                theArchiveContainsCDG =
                                    !theArchive.FindEntry("*.cdg", true).Equals(0);
                            }
                        }

                        if (thisFileInfo.Extension.Contains("cdg") || theArchiveContainsCDG)
                        {
                            string thisChecksum = 
                                IOOperations.GetMD5HashFromFile(
                                    thisFileInfo.FullName);
                            long thisTrackID = 0;

                            using (SQLiteCommand theCommand = theConnection.CreateCommand())
                            {
                                theCommand.CommandText = 
                                    "SELECT [ID] " +
                                    "FROM [Tracks] " +
                                    "WHERE [Checksum] = ?";

                                SQLiteParameter theChecksumParameter = theCommand.CreateParameter();
                                theCommand.Parameters.Add(theChecksumParameter);

                                theChecksumParameter.Value = thisChecksum;

                                thisTrackID = Convert.ToInt64(theCommand.ExecuteScalar());
                            }

                            if (thisTrackID.Equals(0))
                            {
                                using (SQLiteCommand theCommand = theConnection.CreateCommand())
                                {
                                    theCommand.CommandText =
                                        "INSERT INTO [Tracks] ([Path], [Details], [Extension], [Checksum]) " +
                                        "VALUES (?, ?, ?, ?)";

                                    SQLiteParameter thePathParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(thePathParameter);
                                    SQLiteParameter theDetailsParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theDetailsParameter);
                                    SQLiteParameter theExtensionParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theExtensionParameter);
                                    SQLiteParameter theChecksumParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theChecksumParameter);

                                    thePathParameter.Value = thisFileInfo.DirectoryName
                                        .Replace(thisSourceDirectoryInfo.FullName, String.Empty);
                                    theDetailsParameter.Value = thisFileInfo.Name
                                        .Replace(thisFileInfo.Extension, String.Empty);
                                    theExtensionParameter.Value =
                                        thisFileInfo.Extension;
                                    theChecksumParameter.Value =
                                        thisChecksum;

                                    theCommand.ExecuteNonQuery();
                                }

                                if (null != this.Inserting)
                                {
                                    this.Inserting(this, new EventArgs());
                                }
                            }
                            else
                            {
                                using (SQLiteCommand theCommand = theConnection.CreateCommand())
                                {
                                    theCommand.CommandText =
                                        "UPDATE [Tracks] " +
                                        "SET [Path] = ?, " +
                                            "[Details] = ?, " +
                                            "[Extension] = ?, " +
                                            "[ToBeDeleted] = 0 " +
                                        "WHERE [ID] = ?";

                                    SQLiteParameter thePathParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(thePathParameter);
                                    SQLiteParameter theDetailsParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theDetailsParameter);
                                    SQLiteParameter theExtensionParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theExtensionParameter);
                                    SQLiteParameter theIDParameter = theCommand.CreateParameter();
                                    theCommand.Parameters.Add(theIDParameter);

                                    thePathParameter.Value = thisFileInfo.DirectoryName
                                        .Replace(thisSourceDirectoryInfo.FullName, String.Empty);
                                    theDetailsParameter.Value = thisFileInfo.Name
                                        .Replace(thisFileInfo.Extension, String.Empty);
                                    theExtensionParameter.Value =
                                        thisFileInfo.Extension;
                                    theIDParameter.Value = 
                                        thisTrackID;

                                    theCommand.ExecuteNonQuery();
                                }

                                if (null != this.Updating)
                                {
                                    this.Updating(this, new EventArgs());
                                }
                            }
                        }
                    }
                }
            }
            catch { }
        }
Exemplo n.º 29
0
        internal static void manualInstallMod()
        {
            if (isInstalling)
            {
                notifier.Notify(NotificationType.Warning, "Already downloading a mod", "Please try again after a few seconds.");
                return;
            }
            isInstalling = true;

            using (var dlg = new OpenFileDialog()
            {
                CheckFileExists = true,
                CheckPathExists = true,
                DefaultExt = "zip",
                Filter = "Zip Files|*.zip",
                FilterIndex = 1,
                Multiselect = false,
                Title = "Choose the mod zip to install"
            })
            {
                //user pressed ok
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    //open the file in a stream
                    using (var fileStream = dlg.OpenFile())
                    {
                        ZipFile zip = new ZipFile(fileStream);

                        //check integrity
                        if (zip.TestArchive(true))
                        {
                            //look for the map file. It contains the mod name
                            ZipEntry map = zip.Cast<ZipEntry>().FirstOrDefault(a => a.Name.ToLower().EndsWith(".bsp"));

                            if (map != null)
                            {
                                //look for the version file
                                int entry = zip.FindEntry("addoninfo.txt", true);
                                if (entry >= 0)
                                {
                                    string allText = string.Empty;

                                    using (var infoStream = new StreamReader(zip.GetInputStream(entry)))
                                        allText = infoStream.ReadToEnd();

                                    string version = modController.ReadAddonVersion(allText);

                                    if (!string.IsNullOrEmpty(version))
                                    {
                                        Version v = new Version(version);
                                        string name = Path.GetFileNameWithoutExtension(map.Name).ToLower();

                                        //check if this same mod is already installed and if it needs an update
                                        if (modController.clientMods.Any(
                                            a => a.name.ToLower().Equals(name) && new Version(a.version) >= v))
                                        {
                                            MessageBox.Show("The mod you are trying to install is already installed or outdated.", "Mod Manual Install",
                                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                        }
                                        else
                                        {
                                            string targetDir = Path.Combine(d2mpDir, name);
                                            if (Directory.Exists(targetDir))
                                                Directory.Delete(targetDir, true);
                                            //Make the dir again
                                            Directory.CreateDirectory(targetDir);

                                            if (UnzipWithTemp(null, fileStream, targetDir))
                                            {
                                                refreshMods();
                                                log.Info("Mod manually installed!");
                                                notifier.Notify(NotificationType.Success, "Mod installed", "The following mod has been installed successfully: " + name);

                                                var mod = new ClientMod() {name = name, version = v.ToString()};
                                                var msg = new OnInstalledMod() {Mod = mod};

                                                Send(JObject.FromObject(msg).ToString(Formatting.None));

                                                var existing = modController.clientMods.FirstOrDefault(m => m.name == mod.name);
                                                if (existing != null) modController.clientMods.Remove(existing);
                                                
                                                modController.clientMods.Add(mod);
                                            }
                                            else
                                            {
                                                MessageBox.Show("The mod could not be installed. Read the log file for details.", "Mod Manual Install",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Could not read the mod version from the zip file.", "Mod Manual Install",
                                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("No mod info was found in the zip file.", "Mod Manual Install",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                            }
                            else
                            {
                                MessageBox.Show("No mod map was found in the zip file.", "Mod Manual Install",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                        else
                        {
                            MessageBox.Show("The zip file you selected seems to be invalid.", "Mod Manual Install",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                }
            }

            isInstalling = false;
        }
Exemplo n.º 30
0
        public void ZipFileFind()
        {
            string tempFile = null;
            try
            {
                 tempFile = Path.GetTempPath();
            }
            catch (SecurityException)
            {
            }

            Assert.IsNotNull(tempFile, "No permission to execute this test?");

            if (tempFile != null) {
                tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
                MakeZipFile(tempFile, new String[] {"Farriera", "Champagne", "Urban myth" }, 10, "Aha");

                ZipFile zipFile = new ZipFile(tempFile);
                Assert.AreEqual(3, zipFile.Size, "Expected 1 entry");

                int testIndex = zipFile.FindEntry("Farriera", false);
                Assert.AreEqual(0, testIndex, "Case sensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", false) == 0);

                testIndex = zipFile.FindEntry("Farriera", true);
                Assert.AreEqual(0, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "Farriera", true) == 0);

                testIndex = zipFile.FindEntry("urban mYTH", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("urban mYTH", true);
                Assert.AreEqual(2, testIndex, "Case insensitive find failure");
                Assert.IsTrue(string.Compare(zipFile[testIndex].Name, "urban mYTH", true) == 0);

                testIndex = zipFile.FindEntry("Champane.", false);
                Assert.AreEqual(-1, testIndex, "Case sensitive find failure");

                testIndex = zipFile.FindEntry("Champane.", true);
                Assert.AreEqual(-1, testIndex, "Case insensitive find failure");

                zipFile.Close();
                File.Delete(tempFile);
            }
        }
 /// <summary>
 /// 读取所有sheet表的基本信息
 /// </summary>
 public void loadSheetsInfo()
 {
     ZipFile myZip = new ZipFile(filePath);
     mySheetList = new List<SheetStruct>();
     int index = myZip.FindEntry("xl/workbook.xml", true);
     Stream myXmlStream = myZip.GetInputStream(index);
     XmlDocument doc = new XmlDocument();
     doc.Load(myXmlStream);
     XmlNodeList sheets = doc.SelectNodes("/x:workbook/x:sheets/x:sheet", Space.excelName);
     index = myZip.FindEntry("xl/_rels/workbook.xml.rels", true);
     Stream relStream = myZip.GetInputStream(index);
     XmlDocument doc2 = new XmlDocument();
     doc2.Load(relStream);
     int tempIndex = 0;
     foreach (XmlNode sheet in sheets)
     {
         SheetStruct item = new SheetStruct() { name = sheet.Attributes["name"].Value, id = sheet.Attributes["r:id"].Value, index = tempIndex++ };
         item.path = "xl/" + doc2.SelectSingleNode("/x:Relationships/x:Relationship[@Id='" + item.id + "']", Space.excelPackage).Attributes["Target"].Value;
         mySheetList.Add(item);
     }
     myXmlStream.Dispose();
     relStream.Dispose();
     myZip.Close();
 }
Exemplo n.º 32
0
        public static ModEntry ReadMetaData(string ModFile)
        {
            if (!File.Exists(ModFile)) return null;

            try
            {
                using (FileStream streamMod = new FileStream(ModFile, FileMode.Open))
                using (ZipFile zipMod = new ZipFile(streamMod))
                {
                    var metaIndex = zipMod.FindEntry("metadata.xml", true);
                    if (metaIndex == -1) return null;
                    using (StreamReader metaReader = new StreamReader(zipMod.GetInputStream(metaIndex)))
                    {
                        XmlSerializer x = new XmlSerializer(typeof(ModEntry));
                        var metaData = (ModEntry)x.Deserialize(metaReader);
                        return metaData;
                    }
                }
            } catch { return null; }
        }