Close() public method

Closes the ZipFile. If the stream is owned then this also closes the underlying input stream. Once closed, no further instance methods should be called.
/// An i/o error occurs. ///
public Close ( ) : void
return void
Esempio n. 1
1
        /// <summary>
        /// Add files to an existing Zip archive, 
        /// </summary>
        /// <param name="filename">Array of path / filenames to add to the archive</param>
        /// <param name="archive">Zip archive that we want to add the file to</param>
        public void AddToZip(string[] filename, string archive)
        {
            if (!File.Exists(archive))
            {
                return;
            }

            try
            {
                ZipFile zf = new ZipFile(archive);
                zf.BeginUpdate();
                // path relative to the archive
                zf.NameTransform = new ZipNameTransform(Path.GetDirectoryName(archive));
                foreach (var file in filename)
                {
                    // skip if this isn't a real file
                    if (!File.Exists(file))
                    {
                        continue;
                    }
                    zf.Add(file, CompressionMethod.Deflated);
                }
                zf.CommitUpdate();
                zf.Close();
            }
            catch (Exception e)
            {
                if (e.Message != null)
                {
                    var msg = new[] { e.Message };
                    LocDB.Message("defErrMsg", e.Message, msg, LocDB.MessageTypes.Error, LocDB.MessageDefault.First);
                }
            }
        }
        public static void ExtractZipFile(string archiveFilenameIn, string outFolder, 
            Func<ZipEntry, String, bool> entryCheckFunc,
            string password = null)
        {
            ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(archiveFilenameIn);
                zf = new ZipFile(fs);
                if (!String.IsNullOrEmpty(password))
                {
                    zf.Password = password;		// AES encrypted entries are handled automatically
                }
                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;			// Ignore directories
                    }
                    String entryFileName = zipEntry.Name;

                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

                    // Manipulate the output filename here as desired.
                    String fullZipToPath = Path.Combine(outFolder, entryFileName);
                    string directoryName = Path.GetDirectoryName(fullZipToPath);

                    if (entryCheckFunc(zipEntry, fullZipToPath)) continue;

                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

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


                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("ExtractZipFile failed", ex);
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
        }
Esempio n. 3
0
        public void Write(Dictionary <string, byte[]> contents)
        {
            // TODO: Clear existing content?
            pkg.Close();
            pkg = SZipFile.Create(filename);
            pkg.BeginUpdate();

            foreach (var kvp in contents)
            {
                pkg.Add(new StaticMemoryDataSource(kvp.Value), kvp.Key);
            }

            pkg.CommitUpdate();
            pkg.Close();
            pkg = new SZipFile(new MemoryStream(File.ReadAllBytes(filename)));
        }
Esempio n. 4
0
	static public void CompressFolder(string aFolderName, string aFullFileOuputName, string[] ExcludedFolderNames, string[] ExcludedFileNames){
		// Perform some simple parameter checking.  More could be done
		// like checking the target file name is ok, disk space, and lots
		// of other things, but for a demo this covers some obvious traps.
		if (!Directory.Exists(aFolderName)) {
			Debug.Log("Cannot find directory : " + aFolderName);
			return;
		}

		try
		{
			string[] exFileNames = new string[0];
			string[] exFolderNames = new string[0];
			if(ExcludedFileNames != null) exFileNames = ExcludedFileNames;
			if(ExcludedFolderNames != null) exFolderNames = ExcludedFolderNames;
			// Depending on the directory this could be very large and would require more attention
			// in a commercial package.
			List<string> filenames = GenerateFolderFileList(aFolderName, null);
			
			//foreach(string filename in filenames) Debug.Log(filename);
			// 'using' statements guarantee the stream is closed properly which is a big source
			// of problems otherwise.  Its exception safe as well which is great.
			using (ZipOutputStream zipOut = new ZipOutputStream(File.Create(aFullFileOuputName))){
			zipOut.Finish();
			zipOut.Close();
			}
			using(ZipFile s = new ZipFile(aFullFileOuputName)){
					s.BeginUpdate();
					int counter = 0;
					//add the file to the zip file
				   	foreach(string filename in filenames){
						bool include = true;
						string entryName = filename.Replace(aFolderName, "");
						//Debug.Log(entryName);
						foreach(string fn in exFolderNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						foreach(string fn in exFileNames){
							Regex regEx = new Regex(@"^" + fn.Replace(".",@"\."));
							if(regEx.IsMatch(entryName)) include = false;
						}
						if(include){
							s.Add(filename, entryName);
						}
						counter++;
					}
				    //commit the update once we are done
				    s.CommitUpdate();
				    //close the file
				    s.Close();
				}
		}
		catch(Exception ex)
		{
			Debug.Log("Exception during processing" + ex.Message);
			
			// No need to rethrow the exception as for our purposes its handled.
		}
	}
Esempio n. 5
0
            void Work()
            {
                try
                {
                    ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(m_ZipFilePath);
                    m_FileTotalCount = zipFile.Count;
                    zipFile.Close();

                    FastZipEvents zipEvent = new FastZipEvents();
                    zipEvent.Progress      = OnProcess;
                    zipEvent.CompletedFile = OnCompletedFile;

                    FastZip fastZip = new FastZip(zipEvent);
                    fastZip.CreateEmptyDirectories = true;
                    fastZip.ExtractZip(m_ZipFilePath, m_OutDirPath, null);
                    m_IsFinish = true;
                }
                catch (Exception exception)
                {
                    //Log.e(exception.Message);
                    m_ErrorMsg = exception.Message;
                    m_IsError  = true;
                    m_IsFinish = true;
                }
            }
        public static string GetFirstZipEntryWithEnding(string zipfile, string ending)
        {
            #if SHARPZIPLIB
            if (string.IsNullOrEmpty(zipfile))
                return null;

            ZipFile zf = null;
            try
            {
                zf = new ZipFile(zipfile);
            }
            catch (Exception)
            {
                return null;
            }

            string name = null;
            foreach (ZipEntry zipEntry in zf)
            {
                if (zipEntry.Name.ToLower().EndsWith(ending))
                {
                    name = zipEntry.Name;
                    break;
                }
            }
            zf.Close();
            return name;
            #else
            return null;
            #endif
        }
Esempio n. 7
0
        public void Basics()
        {
            const string tempName1 = "a(1).dat";

            MemoryStream target = new MemoryStream();

            string tempFilePath = GetTempFilePath();
            Assert.IsNotNull(tempFilePath, "No permission to execute this test?");

            string addFile = Path.Combine(tempFilePath, tempName1);
            MakeTempFile(addFile, 1);

            try {
                FastZip fastZip = new FastZip();
                fastZip.CreateZip(target, tempFilePath, false, @"a\(1\)\.dat", null);

                MemoryStream archive = new MemoryStream(target.ToArray());
                using (ZipFile zf = new ZipFile(archive)) {
                    Assert.AreEqual(1, zf.Count);
                    ZipEntry entry = zf[0];
                    Assert.AreEqual(tempName1, entry.Name);
                    Assert.AreEqual(1, entry.Size);
                    Assert.IsTrue(zf.TestArchive(true));

                    zf.Close();
                }
            }
            finally {
                File.Delete(tempName1);
            }
        }
Esempio n. 8
0
 public void Dispose()
 {
     if (pkg != null)
     {
         pkg.Close();
     }
 }
        void TestLargeZip(string tempFile, int targetFiles)
        {
            const int BlockSize = 4096;

            byte[] data = new byte[BlockSize];
            byte nextValue = 0;
            for (int i = 0; i < BlockSize; ++i)
            {
                nextValue = ScatterValue(nextValue);
                data[i] = nextValue;
            }

            using (ZipFile zFile = new ZipFile(tempFile))
            {
                Assert.AreEqual(targetFiles, zFile.Count);
                byte[] readData = new byte[BlockSize];
                int readIndex;
                foreach (ZipEntry ze in zFile)
                {
                    Stream s = zFile.GetInputStream(ze);
                    readIndex = 0;
                    while (readIndex < readData.Length)
                    {
                        readIndex += s.Read(readData, readIndex, data.Length - readIndex);
                    }

                    for (int ii = 0; ii < BlockSize; ++ii)
                    {
                        Assert.AreEqual(data[ii], readData[ii]);
                    }
                }
                zFile.Close();
            }
        }
Esempio n. 10
0
        public void Run()
        {
            try
            {
                Stream filestream = File.OpenRead(Filename);

                // SWC file: extract 'library.swf' file
                if (Filename.EndsWith(".swc", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile zfile = new ZipFile(filestream);
                    foreach (ZipEntry entry in zfile)
                    {
                        if (entry.Name.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
                        {
                            ExploreSWF(new MemoryStream(UnzipFile(zfile, entry)));
                        }
                        else if (entry.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
                            && entry.Name.StartsWith("docs/"))
                        {
                            Docs[entry.Name] = UnzipFile(zfile, entry);
                        }
                        else if (entry.Name == "catalog.xml")
                        {
                            Catalog = UnzipFile(zfile, entry);
                        }
                    }
                    zfile.Close();
                    filestream.Close();
                }
                else
                {
                    byte[] data = new byte[filestream.Length];
                    filestream.Read(data, 0, (int)filestream.Length);
                    filestream.Close();
                    Stream dataStream = new MemoryStream(data);

                    // raw ABC bytecode
                    if (Filename.EndsWith(".abc", StringComparison.OrdinalIgnoreCase))
                    {
                        BinaryReader br = new BinaryReader(dataStream);
                        Abc abc = new Abc(br);
                        ExploreABC(abc);
                    }
                    // regular SWF
                    else if (Filename.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
                    {
                        ExploreSWF(dataStream);
                    }
                    else Errors.Add("Error: Not a supported filetype");
                }
            }
            catch (FileNotFoundException)
            {
                Errors.Add("Error: File not found");
            }
            catch (Exception ex)
            {
                Errors.Add("Error: " + ex.Message);
            }
        }
Esempio n. 11
0
        public static void UnzipTo(string filename, Stream toStream)
        {
            ZipFile zf = null;

            try
            {
                FileStream fs = File.OpenRead(filename);
                zf = new ZipFile(fs);

                ZipEntry zipEntry = zf[0];

                String entryFileName = zipEntry.Name;

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

                StreamUtils.Copy(zipStream, toStream, buffer);
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Esempio n. 12
0
 /// <summary>
 /// extract file from zipped resource, and place to temp folder
 /// </summary>
 /// <param name="resource">resource name</param>
 /// <param name="fileName">output name</param>
 /// <param name="OverWriteIfExists">if true,will overwrite the file even if the file exists</param>
 private void ExtractResourceZip(byte[] resource, string fileName, bool OverWriteIfExists = false, int BufferSize = BUFFERSIZE)
 {
     string target = WorkingPath + fileName;
     
     if (OverWriteIfExists || !File.Exists(target))
     {
         ZipFile zip = null;
         FileStream fs = null;
         Stream inStream = null;
         try
         {
             zip = new ZipFile(new MemoryStream(resource));
             inStream = zip.GetInputStream(zip.GetEntry(fileName));
             fs = new FileStream(target, FileMode.Create);
             byte[] buff = new byte[BufferSize];
             int read_count;
             while ((read_count = inStream.Read(buff, 0, BufferSize)) > 0)
             {
                 fs.Write(buff, 0, read_count);
             }
         }
         catch { }
         finally
         {
             if (zip != null) zip.Close();
             if (fs != null) fs.Close();
             if (inStream != null) inStream.Close();
         }
     }
 }
Esempio n. 13
0
        public bool install(string target)
        {
            if (!File.Exists(target))
            {
                return false;
            }
            ZipFile zip = new ZipFile(target);
            bool neednewgamedirectory = true;
            try
            {
                foreach (ZipEntry item in zip)
                {
                    if (item.Name.StartsWith(MeCore.Config.Server.ClientPath ?? ".minecraft"))
                    {
                        neednewgamedirectory = false;
                        continue;
                    }
                    if (!item.IsFile)
                    {
                        continue;
                    }
                    string entryFileName = item.Name;
                    byte[] buffer = new byte[4096];
                    Stream zipStream = zip.GetInputStream(item);
                    string fullZipToPath = "";
                    if (neednewgamedirectory)
                    {
                        fullZipToPath = Path.Combine(MeCore.BaseDirectory, MeCore.Config.Server.ClientPath ?? ".minecraft", entryFileName);
                    }
                    else
                    {
                        fullZipToPath = Path.Combine(MeCore.BaseDirectory, entryFileName);
                    }

                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            catch (Exception ex)
            {
                MeCore.Invoke(new Action(() => MeCore.MainWindow.addNotice(new Notice.CrashErrorBar(string.Format(LangManager.GetLangFromResource("ErrorNameFormat"), DateTime.Now.ToLongTimeString()), ex.ToWellKnownExceptionString()) { ImgSrc = new BitmapImage(new Uri("pack://application:,,,/Resources/error-banner.jpg")) })));

            }
            finally
            {
                if (zip != null)
                {
                    zip.IsStreamOwner = true;
                    zip.Close();
                }
            }
            return true;
        }
Esempio n. 14
0
        public void GetAndUnpackLatestVersion()
        {
            var client = new WebClient();
            string usersTempFolder = Path.GetTempPath();

            string updateZipName = string.Format("v{0}.zip", _newVersion);

            string updateZipLocation = Path.Combine(usersTempFolder, updateZipName);

            client.DownloadFile(Path.Combine(ConfigurationManager.AppSettings["updatePackageAddress"], updateZipName),
                updateZipLocation);

            string updatePackageFullPath = Path.Combine(usersTempFolder, _newVersion.ToString());

            ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(updateZipLocation);
                zf = new ZipFile(fs);

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

                    String entryFileName = zipEntry.Name;

                    var buffer = new byte[4096];
                    Stream zipStream = zf.GetInputStream(zipEntry);

                    String fullZipToPath = Path.Combine(updatePackageFullPath, Path.GetFileName(entryFileName));
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true;
                    zf.Close();
                }
            }

            _updatePackageFullPath = updatePackageFullPath;
        }
Esempio n. 15
0
        public static void RunWholeProcedure()
        {
            Compile.currentMooegeExePath = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\Mooege.exe";
            Compile.currentMooegeDebugFolderPath = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\";
            Compile.mooegeINI = Program.programPath + @"\" + @"Repositories\" + ParseRevision.developerName + "-" + ParseRevision.branchName + "-" + ParseRevision.lastRevision + @"\src\Mooege\bin\Debug\config.ini";

            ZipFile zip = null;
            var events = new FastZipEvents();

            if (ProcessFinder.FindProcess("Mooege") == true)
            {
                ProcessFinder.KillProcess("Mooege");
            }

            FastZip z = new FastZip(events);
            Console.WriteLine("Uncompressing zip file...");
            var stream = new FileStream(Program.programPath + @"\Repositories\" + @"\Mooege.zip", FileMode.Open, FileAccess.Read);
            zip = new ZipFile(stream);
            zip.IsStreamOwner = true; //Closes parent stream when ZipFile.Close is called
            zip.Close();

            var t1 = Task.Factory.StartNew(() => z.ExtractZip(Program.programPath + @"\Repositories\" + @"\Mooege.zip", Program.programPath + @"\" + @"Repositories\", null))
                .ContinueWith(delegate
            {
                //Comenting the lines below because I haven't tested this new way over XP VM or even normal XP.
                //RefreshDesktop.RefreshDesktopPlease(); //Sends a refresh call to desktop, probably this is working for Windows Explorer too, so i'll leave it there for now -wesko
                //Thread.Sleep(2000); //<-This and ^this is needed for madcow to work on VM XP, you need to wait for Windows Explorer to refresh folders or compiling wont find the new mooege folder just uncompressed.
                Console.WriteLine("Uncompress Complete.");
                if (File.Exists(Program.madcowINI))
                {
                    IConfigSource source = new IniConfigSource(Program.madcowINI);
                    String Src = source.Configs["Balloons"].Get("ShowBalloons");

                    if (Src.Contains("1"))
                    {
                        Form1.GlobalAccess.MadCowTrayIcon.ShowBalloonTip(1000, "MadCow", "Uncompress Complete!", ToolTipIcon.Info);
                    }
                }
                Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
                Compile.compileSource(); //Compile solution projects.
                Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
                Form1.GlobalAccess.Invoke((MethodInvoker)delegate { Form1.GlobalAccess.generalProgressBar.PerformStep(); });
                Console.WriteLine("[Process Complete!]");
                if (File.Exists(Program.madcowINI))
                {
                    IConfigSource source = new IniConfigSource(Program.madcowINI);
                    String Src = source.Configs["Balloons"].Get("ShowBalloons");

                    if (Src.Contains("1"))
                    {
                        Form1.GlobalAccess.MadCowTrayIcon.ShowBalloonTip(1000, "MadCow", "Process Complete!", ToolTipIcon.Info);
                    }
                }
            });
        }
Esempio n. 16
0
    public void UndoRedoButton(bool undoFlag)
    {
        string str;

        try
        {
            if (undoFlag == true)
            {
                str = undoList[undoListNum - 1];
                undoListNum--;
            }
            else
            {
                str = undoList[undoListNum + 1];
                undoListNum++;
            }
            mapData.Clear();
            for (int i = 0; i < objIB.Count; i++)
            {
                Destroy(objIB[i]);
            }
            objIB.Clear();

            // 読み込んだ目次テキストファイルからstring配列を作成する
            mapData.AddRange(str.Split('\n'));
            mapData.RemoveAt(mapData.Count - 1); //最後の行は空白なので消す
                                                 //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            for (int i = 0; i < mapData.Count; i++)
            {
                objIB.Add(Instantiate(objIvent) as GameObject);
                objIB[i].transform.SetParent(parentObject.transform, false);
                objIB[i].GetComponentInChildren <Text>().text   = MapDataToButton(mapData[i]);
                objIB[i].GetComponent <IventButton>().buttonNum = i;

                ScenarioFileCheck(i, zf);
            }
            zf.Close();
        }
        catch
        {
            if (undoFlag == true)
            {
                GameObject.Find("Error").GetComponent <Text>().text = "これ以上戻れません。";
            }
            if (undoFlag == false)
            {
                GameObject.Find("Error").GetComponent <Text>().text = "これ以上進めません。";
            }
            StartCoroutine(ErrorWait());
        }
        selectNum = -1;
    }
Esempio n. 17
0
        public static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("SwfOp <file.swf>: list all library symbols of the SWF");
                return;
            }
            string filename = args[args.Length-1];
            operation = (args.Length > 1) ? args[0] : "-list";
            
            // read SWF
            try
            {
                Stream filestream = File.OpenRead(filename);

                // SWC file: extract 'library.swf' file
                if (filename.EndsWith(".swc", StringComparison.OrdinalIgnoreCase))
                {
                    ZipFile zfile = new ZipFile(filestream);
                    foreach(ZipEntry entry in zfile)
                    {
                        if (entry.Name.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
                        {
                            ExploreSWF(new MemoryStream(UnzipFile(zfile, entry)));
                        }
                        else if (entry.Name.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
                            && entry.Name.StartsWith("docs/"))
                        {
                            string docSrc = Encoding.UTF8.GetString(UnzipFile(zfile, entry));
                        }
                    }
                    zfile.Close();
                    filestream.Close();
                }
                else if (filename.EndsWith(".abc", StringComparison.OrdinalIgnoreCase))
                {
                    byte[] data = new byte[filestream.Length];
                    filestream.Read(data, 0, (int)filestream.Length);
                    BinaryReader br = new BinaryReader(new MemoryStream(data));
                    Abc abc = new Abc(br);
                }
                // regular SWF
                else ExploreSWF(new BufferedStream(filestream));
            }
            catch(FileNotFoundException)
            {
                Console.WriteLine("-- SwfOp Error: File not found");
            }
            catch(Exception ex)
            {
                Console.WriteLine("-- SwfOp Error: "+ex.Message);
            }
            Console.ReadLine();
        }
Esempio n. 18
0
        public void Dispose()
        {
            if (pkg != null)
            {
                pkg.Close();
            }

            if (pkgStream != null)
            {
                pkgStream.Dispose();
            }
        }
Esempio n. 19
0
 protected override void Dispose(bool disposing)
 {
     if (!_zip_disposed)
     {
         if (disposing)
         {
             m_zip.Close();
         }
         _zip_disposed = true;
     }
     base.Dispose(disposing);
 }
Esempio n. 20
0
    public void PushPasswordButton()
    {
        string pass;
        string text = "";

        pass = pass2Obj.GetComponent <InputField>().text;
        try
        {
            //閲覧するエントリ
            string extractFile = "[system]password[system].txt";

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            try
            {
                if (ze != null)
                {
                    //閲覧するZIPエントリのStreamを取得
                    System.IO.Stream reader = zf.GetInputStream(ze);
                    //文字コードを指定してStreamReaderを作成
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        reader, System.Text.Encoding.GetEncoding("UTF-8"));
                    // テキストを取り出す
                    text = sr.ReadToEnd();
                    //閉じる
                    sr.Close();
                    reader.Close();
                }
            }
            catch { }

            //閉じる
            zf.Close();
        }
        catch
        {
            GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "シナリオファイルに異常があります。";
            return;
        }
        if (text == "" || text == pass)
        {
            GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "MapScene");
        }
        else
        {
            GameObject.Find("InputFieldPass2Guide").GetComponent <Text>().text = "パスワードが違います。"; return;
        }
    }
Esempio n. 21
0
    public static void ExtractZipFile(string archiveFilenameIn, string password, string outFolder, string justThisFile = null)
    {
        ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
        try
        {
            FileStream fs = File.OpenRead(archiveFilenameIn);
            zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);
            if (!String.IsNullOrEmpty(password))
            {
                zf.Password = password;
            }
            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf)
            {
                if (!zipEntry.IsFile)
                {
                    continue;
                }
                if (!String.IsNullOrEmpty(justThisFile) && zipEntry.Name != justThisFile)
                {
                    continue;
                }
                String entryFileName = zipEntry.Name;
                byte[] buffer        = new byte[4096]; // 4K is optimum
                Stream zipStream     = zf.GetInputStream(zipEntry);

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

                // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                // of the file, but does not waste memory.
                // The "using" will close the stream even if an exception occurs.
                using (FileStream streamWriter = File.Create(fullZipToPath))
                {
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
                }
            }
        }
        finally
        {
            if (zf != null)
            {
                zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                zf.Close();              // Ensure we release resources
            }
        }
    }
Esempio n. 22
0
        public static bool ZipDownloadInfo(DownloadInfo downInfo, string filePath, string ZipedFile)
        {
            bool flag = true;

            if (downInfo.FileList.Count <= 0)
            {
                return(false);
            }
            ICSharpCode.SharpZipLib.Zip.ZipFile file = null;
            try
            {
                file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ZipedFile);
                file.BeginUpdate();
                foreach (SoftFileInfo info in downInfo.FileList)
                {
                    string fileName = Path.Combine(filePath, info.RelativePath);
                    file.Add(fileName);
                }
                file.CommitUpdate();
                file.Close();
            }
            catch
            {
                flag = false;
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                    file = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return(flag);
        }
Esempio n. 23
0
        public static void DecompressFile(string projectFilePath, string targetDirectory)
        {
            FileStream fs   = File.OpenRead(projectFilePath);
            ZipFile    file = new ZipFile(fs);

            foreach (ZipEntry zipEntry in file)
            {
                if (!zipEntry.IsFile)
                {
                    // Ignore directories but create them in case they're empty
                    Directory.CreateDirectory(Path.Combine(targetDirectory, zipEntry.Name));
                    continue;
                }

                //exclude nuget metadata files
                string[] excludedFiles = { ".nuspec", ".xml", ".rels", ".psmdcp" };
                if (excludedFiles.Any(e => Path.GetExtension(zipEntry.Name) == e))
                {
                    continue;
                }

                string entryFileName = Uri.UnescapeDataString(zipEntry.Name);

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

                // Manipulate the output filename here as desired.
                string fullZipToPath = Path.Combine(targetDirectory, entryFileName);
                string directoryName = Path.GetDirectoryName(fullZipToPath);

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

                // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                // of the file, but does not waste memory.
                // The "using" will close the stream even if an exception occurs.
                using (FileStream streamWriter = File.Create(fullZipToPath))
                    StreamUtils.Copy(zipStream, streamWriter, buffer);
            }

            if (file != null)
            {
                file.IsStreamOwner = true;
                file.Close();
            }
        }
        public IList<string> Unzip(string archiveFile, string destinationDirectory)
        {
            IList<string> files = new List<string>();
            ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(archiveFile);
                zf = new ZipFile(fs);
                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }
                    String entryFileName = zipEntry.Name;
                    // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName);
                    // Optionally match entrynames against a selection list here to skip as desired.
                    // The unpacked length is available in the zipEntry.Size property.

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

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

                    // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                    // of the file, but does not waste memory.
                    // The "using" will close the stream even if an exception occurs.
                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                    files.Add(fullZipToPath);
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
            return files;
        }
Esempio n. 25
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();
				}
			}
		}
Esempio n. 26
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;
 }
Esempio n. 27
0
    //目次ファイルを読み込み、進行度に合わせてファイルを拾ってくる。
    private void LoadMapData(string path)
    {
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //閲覧するZIPエントリのStreamを取得
                System.IO.Stream reader = zf.GetInputStream(ze);
                //文字コードを指定してStreamReaderを作成
                System.IO.StreamReader sr = new System.IO.StreamReader(
                    reader, System.Text.Encoding.GetEncoding("UTF-8"));
                // テキストを取り出す
                string text = sr.ReadToEnd();

                // 読み込んだ目次テキストファイルからstring配列を作成する
                mapData = text.Split('\n');
                //閉じる
                sr.Close();
                reader.Close();
                mapLoad = true;
            }
            else
            {
                obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常");
                ErrorBack();
                mapData = new string[0];
            }
            //閉じる
            zf.Close();
        }
        catch
        {
            obj.GetComponent <Text>().text = ("[エラー]\nシナリオファイルの異常");
            ErrorBack();
            mapData = new string[0];
        }
    }
Esempio n. 28
0
		public InstallableAddIn(string fileName, bool isPackage)
		{
			this.fileName = fileName;
			this.isPackage = isPackage;
			if (isPackage) {
				ZipFile file = new ZipFile(fileName);
				try {
					LoadAddInFromZip(file);
				} finally {
					file.Close();
				}
			} else {
				addIn = AddIn.Load(fileName);
			}
			if (addIn.Manifest.PrimaryIdentity == null)
				throw new AddInLoadException(ResourceService.GetString("AddInManager.AddInMustHaveIdentity"));
		}
 public InstallableAddIn(string fileName, bool isPackage)
 {
     this.fileName = fileName;
     this.isPackage = isPackage;
     if (isPackage) {
         ZipFile file = new ZipFile(fileName);
         try {
             LoadAddInFromZip(file);
         } finally {
             file.Close();
         }
     } else {
         addIn = AddIn.Load(fileName);
     }
     if (addIn.Manifest.PrimaryIdentity == null)
         throw new AddInLoadException("The AddIn must have an <Identity> for use with the AddIn-Manager.");
 }
Esempio n. 30
0
 static void ExtractZipDirectory(string archname, string directoryname)
 {
     // 4K is optimum
     byte[] buffer = new byte[4096];
     try
     {
         using (System.IO.Stream source = System.IO.File.Open(archname, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
         {
             //! archive file load to stream
             ICSharpCode.SharpZipLib.Zip.ZipFile zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(source);
             try
             {
                 foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry entry in zipFile)
                 {
                     if (!entry.IsFile)
                     {
                         continue;
                     }
                     if (entry.IsCrypted)
                     {
                         throw new Exception("Compress file encrypted.");
                     }
                     string filetobecreate = System.IO.Path.Combine(directoryname, entry.Name);
                     using (System.IO.Stream data = zipFile.GetInputStream(entry))
                     {
                         using (System.IO.Stream write = System.IO.File.Open(filetobecreate, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None))
                         {
                             ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(data, write, buffer);
                             write.Close();
                         }
                         data.Close();
                     }
                 }
             }
             finally
             {
                 zipFile.IsStreamOwner = true;
                 zipFile.Close();
             }
         }
     }
     catch (System.IO.IOException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Esempio n. 31
0
        public Image GetImage(Stream data)
        {
            ZipFile zip = null;
              try {
            if (data.CanSeek == false){
              return GetDefaultImage();
            }

            zip = new ZipFile(data);

            foreach (ZipEntry entry in zip ) {
              if (IsImageEntry(entry)) {
            try {
              using (Stream input = zip.GetInputStream(entry))
              using (Image original = Image.FromStream(input)) {
                return new Bitmap(original);
              }
            }
            catch (ZipException e) {
              Debug.WriteLine(e);
              continue;
            }
            catch (ArgumentException e) {
              Debug.WriteLine(e);
              continue;
            }
              }
            }
            return GetDefaultImage();
              }
              catch (IOException e) {
            Debug.WriteLine(e);
            return GetDefaultImage();
              }
              catch (ZipException e) {
            Debug.WriteLine(e);
            return GetDefaultImage();
              }
              finally {
            Debug.WriteLine("finally");
            if (zip != null) {
              zip.Close();
            }
              }
        }
Esempio n. 32
0
        public FileStorageEntry[] GetAllEntrys()
        {
            List<FileStorageEntry> es = new List<FileStorageEntry>();
            ZipFile zipFile = new ZipFile(FileLoc);
            foreach (ZipEntry e in zipFile)
            {
                es.Add(new FileStorageEntry()
                    {
                        Created = e.DateTime,
                        Location = e.Name,
                        IsDir = e.IsDirectory
                    });
            }

            zipFile.Close();

            return es.ToArray();
        }
Esempio n. 33
0
        public FileStorageEntry[] GetAllEntrys()
        {
            List<FileStorageEntry> es = new List<FileStorageEntry>();
            ZipFile zipFile = new ZipFile(this.zipArchive);
            foreach (ZipEntry e in zipFile)
            {
                es.Add(new FileStorageEntry()
                    {
                        Created = e.DateTime,
                        Location = e.Name,
                        IsDir = e.IsDirectory
                    });
            }

            zipFile.IsStreamOwner = false; zipFile.Close();

            this.zipArchive.Position = 0;
            return es.ToArray();
        }
Esempio n. 34
0
        static void ExtractZipFile(Stream stream, string outFolder)
        {
            ZipFile zipFile = null;

            try
            {
                zipFile = new ZipFile(stream);

                foreach (ZipEntry zipEntry in zipFile)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;
                    }

                    var entryFileName = zipEntry.Name;

                    var buffer = new byte[4096];
                    var zipStream = zipFile.GetInputStream(zipEntry);

                    var fullOutFolder = Path.Combine(outFolder, entryFileName);
                    var directoryName = Path.GetDirectoryName(fullOutFolder);

                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    using (var streamWriter = File.Create(fullOutFolder))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.IsStreamOwner = true;
                    zipFile.Close();
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Распаковывает указанный архив в указанную директорию
        /// </summary>
        /// <param name="fZip">Путь до архива</param>
        /// <param name="Destination">Директория назначения</param>
        /// <returns></returns>
        public static bool UnpackZIP(Stream stream, string Destination)
        {
            try
            {
                if (Directory.Exists(Destination))
                    Directory.Delete(Destination, true);
            }
            catch { return false; }

            ZipFile zf = null;
            bool IsSuccess = true;

            try
            {
                zf = new ZipFile(stream);
                foreach (ZipEntry zipEntry in zf)
                {
                    if (!zipEntry.IsFile)
                        continue;
                    byte[] buffer = new byte[4096];
                    Stream zipStream = zf.GetInputStream(zipEntry);
                    string fullZipToPath = Path.Combine(Destination, zipEntry.Name.Replace('/', '\\'));
                    string directoryName = Path.GetDirectoryName(fullZipToPath);
                    if (directoryName.Length > 0)
                        Directory.CreateDirectory(directoryName);

                    using (FileStream streamWriter = File.Create(fullZipToPath))
                    {
                        StreamUtils.Copy(zipStream, streamWriter, buffer);
                    }
                }
            }
            catch { IsSuccess = false; }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true;
                    zf.Close();
                }
            }
            return IsSuccess;
        }
Esempio n. 36
0
 /// <summary>
 /// Packs the file to stream.
 /// </summary>
 /// <returns>The file to stream.</returns>
 /// <param name="files">Files.</param>
 public static Stream PackFileToStream(List <KeyValuePair <string, string> > files)
 {
     try
     {
         var stream = new MemoryStream();
         ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(stream);
         zip.BeginUpdate();
         foreach (var file in files)
         {
             zip.Add(file.Key, file.Value);
         }
         zip.CommitUpdate();
         zip.Close();
         return(stream);
     }
     catch (Exception)
     {
         return(null);
     }
 }
Esempio n. 37
0
        /// <summary>
        /// Packs the files.
        /// </summary>
        /// <returns>The files.</returns>
        /// <param name="zipFile">Zip file.</param>
        /// <param name="files">Key:文件全路径,Value:压缩文件里的文件名</param>
        public static string PackFiles(string zipFile, List <KeyValuePair <string, string> > files)
        {
            try
            {
                ICSharpCode.SharpZipLib.Zip.ZipFile zip = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(zipFile);
                zip.BeginUpdate();

                foreach (var s in files)
                {
                    zip.Add(s.Key, s.Value);
                }
                zip.CommitUpdate();
                zip.Close();
                return(zipFile);
            }
            catch (Exception)
            {
                return("");
            }
        }
Esempio n. 38
0
    //startのタイミングでフリーイベントの一覧表を取得し、条件を満たしているものはボタンを作成(Mapシーン限定)
    private void GetFreeIvent(string path)
    {
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //閲覧するZIPエントリのStreamを取得
                System.IO.Stream reader = zf.GetInputStream(ze);
                //文字コードを指定してStreamReaderを作成
                System.IO.StreamReader sr = new System.IO.StreamReader(
                    reader, System.Text.Encoding.GetEncoding("UTF-8"));
                // テキストを取り出す
                string text = sr.ReadToEnd();
                text = text.Replace("[system]任意イベント", "[system]任意イベントCS");
                // 読み込んだ目次テキストファイルからstring配列を作成する
                mapData = text.Split('\n');
                //閉じる
                sr.Close();
                reader.Close();
            }
            else
            {
                SceneManager.LoadScene("TitleScene");
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
Esempio n. 39
0
    //アイテム画像ファイルを拾ってくる。
    private void LoadItem(string path)
    {
        byte[] buffer;
        try
        {
            //閲覧するエントリ
            string extractFile = path;
            ICSharpCode.SharpZipLib.Zip.ZipFile zf;
            //ZipFileオブジェクトの作成
            zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("[system]進行中シナリオ", ""));//説明に書かれてる以外のエラーが出てる。

            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            if (ze != null)
            {
                //pngファイルの場合
                if (path.Substring(path.Length - 4) == ".png" || path.Substring(path.Length - 4) == ".PNG" || path.Substring(path.Length - 4) == ".jpg" || path.Substring(path.Length - 4) == ".JPG")
                {
                    //閲覧するZIPエントリのStreamを取得
                    Stream fs = zf.GetInputStream(ze);
                    buffer = ReadBinaryData(fs);//bufferにbyte[]になったファイルを読み込み

                    // 画像を取り出す

                    //byteからTexture2D作成
                    Texture2D texture = new Texture2D(1, 1);
                    texture.LoadImage(buffer);
                    obj6.GetComponent <Image>().sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                    //閉じる
                    fs.Close();
                }
            }
            //閉じる
            zf.Close();
        }
        catch
        {
        }
    }
Esempio n. 40
0
        public ZipBackup(string filePath)
        {
            FilePath = filePath;

            var archive = new ZipFile(FilePath);

            foreach (var m in (from ZipEntry x in archive
                        where x.Name.ToLower().StartsWith("data/")
                        let m = "." + x.Name.Substring(4)
                        select m))
            {
                var name = m.Substring(0, m.LastIndexOf("."));
                var hash = m.Substring(m.LastIndexOf(".") + 1);
                _names.Add(name);
                _hashes.Add(name.ToLower(), hash);
            }

            archive.Close();

            ReadInfo ();
        }
Esempio n. 41
0
        /// <summary>
        /// 根据压缩包路径读取此压缩包内文件个数
        /// </summary>
        /// <param name="zipFilePath"></param>
        /// <returns></returns>
        public static int FileInZipCount(string zipFilePath)
        {
            int        iNew;
            ZipEntry   zipEntry_ = null;
            FileStream fsFile_   = null;
            ZipFile    zipFile_  = null;

            try
            {
                fsFile_  = new FileStream(zipFilePath, FileMode.OpenOrCreate);
                zipFile_ = new ICSharpCode.SharpZipLib.Zip.ZipFile(fsFile_);
                long l_New = zipFile_.Count;
                iNew = System.Convert.ToInt32(l_New);
                return(iNew);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message + "/" + ex.StackTrace);
                return(0);
            }
            finally
            {
                if (zipFile_ != null)
                {
                    if (zipFile_.IsUpdating)
                    {
                        zipFile_.CommitUpdate();
                    }
                    zipFile_.Close();
                }
                if (fsFile_ != null)
                {
                    fsFile_.Close();
                }
                if (zipEntry_ != null)
                {
                    zipEntry_ = null;
                }
            }
        }
Esempio n. 42
0
 public static void Extract(string archiveFilenameIn, string outFolder, string password = null)
 {
     ZipFile zipFile = null;
     try
     {
         FileStream file = File.OpenRead(archiveFilenameIn);
         zipFile = new ZipFile(file);
         if (!string.IsNullOrEmpty(password))
         {
             zipFile.Password = password;
         }
         foreach (ZipEntry zipEntry in zipFile)
         {
             if (zipEntry.IsFile)
             {
                 string name = zipEntry.Name;
                 byte[] buffer = new byte[4096];
                 Stream inputStream = zipFile.GetInputStream(zipEntry);
                 string path = Path.Combine(outFolder, name);
                 string directoryName = Path.GetDirectoryName(path);
                 if (directoryName.Length > 0)
                 {
                     Directory.CreateDirectory(directoryName);
                 }
                 using (FileStream fileStream = File.Create(path))
                 {
                     StreamUtils.Copy(inputStream, fileStream, buffer);
                 }
             }
         }
     }
     finally
     {
         if (zipFile != null)
         {
             zipFile.IsStreamOwner = true;
             zipFile.Close();
         }
     }
 }
Esempio n. 43
0
    public void GetStartPoint()
    {
        string[] strs;
        //閲覧するエントリ
        string extractFile = "[system]command1[system]PC版スタート地点[system].txt";

        //ZipFileオブジェクトの作成
        ICSharpCode.SharpZipLib.Zip.ZipFile zf =
            new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
        zf.Password = Secret.SecretString.zipPass;
        //展開するエントリを探す
        ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

        if (ze != null)
        {
            //閲覧するZIPエントリのStreamを取得
            System.IO.Stream reader = zf.GetInputStream(ze);
            //文字コードを指定してStreamReaderを作成
            System.IO.StreamReader sr = new System.IO.StreamReader(
                reader, System.Text.Encoding.GetEncoding("UTF-8"));
            // テキストを取り出す
            string text = sr.ReadToEnd();

            // 読み込んだ目次テキストファイルからstring配列を作成する
            strs = text.Split('\n');
            strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
            //閉じる
            sr.Close();
            reader.Close();
        }
        else
        {
            strs    = new string[2];
            strs[0] = "35.010348"; strs[1] = "135.768738";
        }
        //閉じる
        zf.Close();
        latitude = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
    }
Esempio n. 44
0
        internal ArcFile OpenZipArchive(ArcView file, Stream input)
        {
            SharpZip.ZipStrings.CodePage = Properties.Settings.Default.ZIPEncodingCP;
            var zip = new SharpZip.ZipFile(input);

            try
            {
                var  files         = zip.Cast <SharpZip.ZipEntry>().Where(z => !z.IsDirectory);
                bool has_encrypted = files.Any(z => z.IsCrypted);
                if (has_encrypted)
                {
                    zip.Password = QueryPassword(file);
                }
                var dir = files.Select(z => new ZipEntry(z) as Entry).ToList();
                return(new PkZipArchive(file, this, dir, zip));
            }
            catch
            {
                zip.Close();
                throw;
            }
        }
Esempio n. 45
0
 private static long CompressFile(FileInfo fi)
 {
     long w = 0;
     if (!overwrite && File.Exists(fi.Name.Replace(fi.Extension, ".zip")))
     {
         if (!quiet)
             Print(String.Format("\r !!   Skipping extant file {0}", fi.Name), ConsoleColor.DarkCyan);
         return -1;
     }
     using (Stream z = File.Open(fi.Name.Replace(fi.Extension, ".zip"), FileMode.OpenOrCreate, FileAccess.ReadWrite))
     {
         using (ZipFile zip = new ZipFile(z))
         {
             zip.BeginUpdate();
             zip.Add(fi.Name);
             zip.CommitUpdate();
             w = z.Length;
             zip.Close();
         }
         return w;
     }
 }
Esempio n. 46
0
        public static IEnumerable<File> Extract(Stream fileStream)
        {
            var filesInPackage = new List<File>();
            ZipFile zipFile = null;
            try
            {
                zipFile = new ZipFile(fileStream);
                foreach (ZipEntry zipEntry in zipFile)
                {
                    if (!zipEntry.IsFile)
                    {
                        continue;			// Ignore directories
                    }

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

                    using (var memoryStream = new MemoryStream())
                    {
                        StreamUtils.Copy(zipStream, memoryStream, buffer);
                        filesInPackage.Add(new File
                        {
                            Data = memoryStream.ToArray(),
                            Filename = zipEntry.Name
                        });
                    }
                }

                return filesInPackage;
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zipFile.Close(); // Ensure we release resources
                }
            }
        }
Esempio n. 47
0
 public static void UnZipFB2Archive(string archiveFileName, string outputFolder, bool onlyFB2, bool showProgress)
 {
     string directoryName = outputFolder;
     // create directory
     if (directoryName.Length > 0)
     {
         Directory.CreateDirectory(directoryName);
     }
     ZipFile zf = new ZipFile(File.OpenRead(archiveFileName));
     try
     {
         foreach (ZipEntry zipEntry in zf)
         {
             string fileName = directoryName + "\\" + Path.GetFileName(zipEntry.Name);
             if (IsFileNameCorrect(fileName, onlyFB2))
             {
                 if (showProgress)
                 {
                     Console.WriteLine(string.Format("Extract file: {0}", Path.GetFileName(fileName)));
                 }
                 byte[] data = new byte[4096];
                 Stream zipStream = zf.GetInputStream(zipEntry);
                 using (FileStream streamWriter = File.Create(fileName))
                 {
                     StreamUtils.Copy(zipStream, streamWriter, data);
                 }
             }
         }
     }
     finally
     {
         if (zf != null)
         {
             zf.IsStreamOwner = true;
             zf.Close();
         }
     }
 }
Esempio n. 48
0
        private static Stream getStream(string filename, string extension)
        {
            var stream = new FileStream(filename, FileMode.Open,
                            FileAccess.Read, FileShare.ReadWrite, 1024 * 64);
            switch (extension)
            {
                case ".eu4": return stream;
                case ".gz": return new GZipStream(stream, CompressionMode.Decompress);
                case ".zip":
                    var zf = new ZipFile(stream);
                    foreach (ZipEntry e in zf)
                    {
                        if (Path.GetExtension(e.Name) == ".eu4")
                            return zf.GetInputStream(e);
                    }

                    zf.Close();
                    throw new ApplicationException("EU4 file not found in zip file");
                default:
                    stream.Close();
                    throw new ArgumentException("Extension not recognized: " + extension);
            }
        }
Esempio n. 49
0
        /// <summary>
        /// 根据压缩包路径读取此压缩包内文件个数
        /// </summary>
        /// <param name="zipFilePath"></param>
        /// <returns></returns>
        public static int CountZipFile(string zipFilePath)
        {
            ZipFile zipFile = null;

            try
            {
                using (zipFile = new ICSharpCode.SharpZipLib.Zip.ZipFile(zipFilePath))
                {
                    long l_New = zipFile.Count;
                    return(Convert.ToInt32(l_New));
                }
            }
            catch
            {
                return(0);
            }
            finally
            {
                if (zipFile != null)
                {
                    zipFile.Close();
                }
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Counts the file in the zip.
        /// </summary>
        /// <returns>The total number of files found.</returns>
        public long CountFiles()
        {
            long count = 0;

            ZipFile zf = null;

            try
            {
                FileStream fs = File.OpenRead(ZipFilePath);
                zf = new ZipFile(fs);

                count = zf.Count;
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true;
                    zf.Close();
                }
            }

            return count;
        }
Esempio n. 51
0
    private IEnumerator NCBIE(string str1, string str2, bool flag)
    {
        int           inum = 0;
        string        tmp1, tmp2;
        List <string> tmpList = new List <string>();

        tmp1 = "[system]" + str1 + ".txt";
        tmp2 = str2;
        //全てのコマンドファイル、イベントファイル、マップデータを開き、コマンド名([system]~~××.txt)をtmp1に、イベント名(××.txt)をtmp2に変換する。

        //ZipFileオブジェクトの作成
        ICSharpCode.SharpZipLib.Zip.ZipFile zf =
            new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
        zf.Password = Secret.SecretString.zipPass;
        foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf)
        {
            if ((ze.Name != tmp2 && ze.Name == tmp1))
            {
                //他のイベントと名前がかぶっていれば、名前変更ではなくイベント紐付けが目的だと判断。コピーはしない。
                zf.Close();
                yield break;
            }
        }
        //ZipFileの更新を開始
        zf.BeginUpdate();

        //展開するエントリを探す
        foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze in zf)
        {
            if (ze.Name.Substring(ze.Name.Length - 4) == ".txt" && !tmpList.Contains(ze.Name) && ze.Name != "[system]mapdata[system].txt")
            {
                //閲覧するZIPエントリのStreamを取得
                Stream reader = zf.GetInputStream(ze);
                //文字コードを指定してStreamReaderを作成
                StreamReader sr = new StreamReader(
                    reader, System.Text.Encoding.GetEncoding("UTF-8"));
                // テキストを取り出す
                string text = sr.ReadToEnd();
                sr.Close();
                reader.Close();
                string text2 = text;
                // 読み込んだ目次テキストファイルからstring配列を作成する
                text = text.Replace(tmp2, tmp1);
                if (text2 == text)
                {
                    continue;
                }
                StreamWriter sw = new StreamWriter(@GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp" + inum.ToString() + ".txt", false, System.Text.Encoding.GetEncoding("UTF-8"));
                //TextBox1.Textの内容を書き込む
                sw.Write(text);
                //閉じる
                sw.Close();

                //ファイル名自体も置換
                string tmpName;
                tmpName = ze.Name;
                tmpName = tmpName.Replace(tmp2, tmp1);
                if (flag == false)
                {
                    zf.Delete(ze.Name);
                }                                         //他から関連付けされていないなら、旧コマンドファイルはもう使わないので削除。
                zf.Add("tmp" + inum.ToString() + ".txt", tmpName);
                inum++;
                tmpList.Add(tmpName);
            }
        }
        //ZipFileの更新をコミット
        zf.CommitUpdate();

        //閉じる
        zf.Close();
        for (int i = 0; i < inum; i++)
        {
            File.Delete(@GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp" + i.ToString() + ".txt");
        }
        for (int i = 0; i < undoList.Count; i++)
        {
            undoList[i] = undoList[i].Replace(tmp2, tmp1);
        }
    }
Esempio n. 52
0
        /// <summary>
        /// Extracts the first image from a zip file.
        /// </summary>
        /// <param name="archiveFilenameIn">
        /// The archive filename in.
        /// </param>
        /// <param name="outFolder">
        /// The out folder.
        /// </param>
        public static IMediaModel ExtractZipFileFirstImage(DirectoryInfo argCurrentDataFolder, MediaModel argExistingMediaModel, IMediaModel argNewMediaModel)
        {
            ICSharpCode.SharpZipLib.Zip.ZipFile zf = null;
            try
            {
                FileStream fs = File.OpenRead(argExistingMediaModel.MediaStorageFilePath);
                zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);

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

                    string entryFileName = zipEntry.Name;

                    // check for image TODO do proper mimetype mapping. See https://github.com/samuelneff/MimeTypeMap
                    if (SharedSharp.Common.SharedSharpGeneral.MimeMimeTypeGet(CommonRoutines.MimeFileContentTypeGet(Path.GetExtension(zipEntry.Name))) != "image")
                    {
                        continue;
                    }
                    else
                    {
                        // set extension
                        argNewMediaModel.OriginalFilePath = Path.ChangeExtension(argNewMediaModel.OriginalFilePath, Path.GetExtension(zipEntry.Name));

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

                        // Unzip file in buffered chunks. This is just as fast as unpacking to a
                        // buffer the full size of the file, but does not waste memory. The "using"
                        // will close the stream even if an exception occurs.
                        using (FileStream streamWriter = File.Create(System.IO.Path.Combine(argCurrentDataFolder.FullName, argNewMediaModel.OriginalFilePath)))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }

                        // exit early
                        return(argNewMediaModel);
                    }
                }

                fs.Close();

                // Exit
                return(new MediaModel());
            }
            catch (DirectoryNotFoundException ex)
            {
                ErrorInfo t = new ErrorInfo("Directory not found when trying to create image from ZIP file")
                {
                    { "Original ID", argExistingMediaModel.Id },
                    { "Original File", argExistingMediaModel.MediaStorageFilePath },
                    { "Clipped Id", argNewMediaModel.Id },
                    { "New path", "pdfimage" }
                };

                App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t);

                return(new MediaModel());
            }
            catch (Exception ex)
            {
                ErrorInfo t = new ErrorInfo("Exception when trying to create image from ZIP file")
                {
                    { "Original ID", argExistingMediaModel.Id },
                    { "Original File", argExistingMediaModel.MediaStorageFilePath },
                    { "Clipped Id", argNewMediaModel.Id }
                };

                App.Current.Services.GetService <IErrorNotifications>().NotifyException("PDF to Image", ex, t);

                return(new MediaModel());
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close();              // Ensure we release resources
                }
            }
        }
Esempio n. 53
0
    //[system]mapdata.txtファイルを書き出す関数
    public void MakeMapDataFile()
    {
        //List<string> tmpList = new List<string>();
        List <string> notUseList = new List <string>();

        try
        {
            string str = "";
            //ZIP書庫のパス
            string zipPath = PlayerPrefs.GetString("進行中シナリオ", "");
            //書庫に追加するファイルのパス
            string file = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "[system]mapdata[system].txt";

            //先に[system]mapdata.txtを一時的に書き出しておく。
            for (int i = 0; i < mapData.Count; i++)
            {
                if (mapData[i].Replace("\n", "").Replace("\r", "") == "")
                {
                    continue;
                }
                str = str + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n";
            }
            str = str + "[END]";
            System.IO.File.WriteAllText(file, str);

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath);
            zf.Password = Secret.SecretString.zipPass;

            //先にzip上のmapdataを更新しておく(以降でzip上のmapdataを基に、使っているファイルを判別して不使用ファイルを消す操作をするから)
            //ZipFileの更新を開始
            zf.BeginUpdate();
            //ZIP書庫に一時的に書きだしておいたファイルを追加する
            zf.Add(file, System.IO.Path.GetFileName(file));
            //ZipFileの更新をコミット
            zf.CommitUpdate();


            //以下、不使用データの削除処理
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry("[system]mapdata[system].txt");
            tmpList.Clear();
            FileSearchLoop(ze, zf);

            tmpList.Add("[system]mapdata[system].txt"); tmpList.Add("[system]password[system].txt"); tmpList.Add("[system]commandFileNum[system].txt");
            tmpList.Add("[system]command1[system]PC版スタート地点[system].txt"); tmpList.Add("[system]PC版スタート地点[system].txt");

            foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry ze3 in zf)
            {
                bool useFlag = false;
                foreach (string tmpStr in tmpList)
                {
                    if (tmpStr == ze3.Name)
                    {
                        useFlag = true;
                    }
                }
                if (useFlag == false)
                {
                    string tmpStr = ze3.Name; notUseList.Add(tmpStr);
                }
            }

            //ZipFileの更新を開始
            zf.BeginUpdate();

            foreach (string tmpStr in notUseList)
            {
                zf.Delete(tmpStr);
            }                                                           //notUseListのファイルを消す。

            //ZipFileの更新をコミット
            zf.CommitUpdate();

            //閉じる
            zf.Close();

            //一時的に書きだした[system]mapdata.txtを消去する。
            System.IO.File.Delete(file);
        }
        catch { }
    }
Esempio n. 54
0
    //インプットフィールドの入力を受け取る関数
    public void InputDecideButton()
    {
        string str3;
        string PLIvent = "";

        string[] tmp;
        string   tmpStr;
        bool     doubleconnectflag = false;

        try
        {
            if (inputField[0].text.Contains("[system]"))
            {
                GameObject.Find("Error").GetComponent <Text>().text = "「<color=red>[system]</color>」という文字列は使用禁止です。(システム処理の識別語にしています)"; StartCoroutine(ErrorWait()); return;
            }
            if (selectNum > 0)
            {
                if (PLIventToggle.GetComponent <Toggle>().isOn)
                {
                    PLIvent = " [system]任意イベント";
                }
                if (mapData.Count <= selectNum)
                {
                    for (int i = mapData.Count; i <= selectNum; i++)
                    {
                        mapData.Add(",,,,,,,,,,,[system]空イベント.txt");
                    }
                }                                                                                                                                    //mapDataの要素数をselectNumが越えたら配列の要素数を合わせて増やす。中身は空でOK。(イベント追加されるとmapData.Count以上の番号を持つイベントができるため)
                tmp = mapData[selectNum].Split(',');
                mapData[selectNum] = inputField[1].text + "," + inputField[2].text + "," + inputField[3].text + "," + inputField[4].text + "," + inputField[5].text + "," + inputField[6].text + "," + inputField[7].text + "," + inputField[8].text + "," + inputField[9].text + "," + inputField[10].text + "," + inputField[11].text + PLIvent + ",[system]" + inputField[0].text + ".txt\n";
                objIB[selectNum].GetComponentInChildren <Text>().text = MapDataToButton(mapData[selectNum]);

                //コピー元と同一イベントを参照しているものがあるか判定
                tmpStr = tmp[tmp.Length - 1].Replace("\n", "").Replace("\r", "");
                for (int i = 0; i < mapData.Count; i++)
                {
                    tmp = mapData[i].Split(','); if (tmp[tmp.Length - 1].Replace("\n", "").Replace("\r", "") == tmpStr)
                    {
                        doubleconnectflag = true;
                    }
                }
                //コピー先と同一イベント名がない場合(NCBIE内で判定)は関連コマンドファイルのイベント名変更
                StartCoroutine(NCBIE(inputField[0].text, tmpStr, doubleconnectflag));

                //ファイルチェックして(未)をつける
                //ZipFileオブジェクトの作成
                ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                    new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
                zf.Password = Secret.SecretString.zipPass;
                ScenarioFileCheck(selectNum, zf);
                zf.Close();

                if (inputField[1].text != "" && inputField[2].text != "")
                {
                    latitude = Convert.ToDouble(inputField[1].text); longitude = Convert.ToDouble(inputField[2].text);
                }
                str3 = "";
                for (int i = 0; i < mapData.Count; i++)
                {
                    if (mapData[i].Replace("\n", "").Replace("\r", "") == "")
                    {
                        continue;
                    }
                    str3 = str3 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n";
                }
                undoList.Add(str3);
                undoListNum = undoList.Count - 1;
            }
            else if (selectNum == 0)
            {
                //座標を突っ込むだけのイベントファイルを作成。内容は座標設定→マップワンス
                string str  = "";                                                  //イベントファイルの1行目はファイル名入れない
                string str2 = "[system]command1[system]PC版スタート地点[system].txt\r\n"; //一行目はファイル名を示す部分。
                                                                                   //ZIP書庫のパス
                string zipPath = PlayerPrefs.GetString("進行中シナリオ", "");
                //書庫に追加するファイルのパス
                string file  = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + @"[system]PC版スタート地点[system].txt";
                string file2 = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + @"[system]command1[system]PC版スタート地点[system].txt";

                //先にテキストファイルを一時的に書き出しておく。
                str  = str + System.IO.Path.GetFileName(file2);
                str2 = str2 + "PlaceChange:" + inputField[12].text + "," + inputField[13].text + "\r\nBackText:シナリオ初期データ設定中,false\r\nMap:Once\r\n[END]";

                System.IO.File.WriteAllText(file, str);
                System.IO.File.WriteAllText(file2, str2);
                //ZipFileオブジェクトの作成
                ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                    new ICSharpCode.SharpZipLib.Zip.ZipFile(zipPath);
                zf.Password = Secret.SecretString.zipPass;
                //ZipFileの更新を開始
                zf.BeginUpdate();

                //ZIP内のエントリの名前を決定する
                string f  = System.IO.Path.GetFileName(file);
                string f2 = System.IO.Path.GetFileName(file2);
                //ZIP書庫に一時的に書きだしておいたファイルを追加する
                zf.Add(file, f);
                zf.Add(file2, f2);
                //ZipFileの更新をコミット
                zf.CommitUpdate();

                objIB[selectNum].GetComponentInChildren <Text>().text = MapDataToButton(mapData[selectNum]);
                ScenarioFileCheck(selectNum, zf);


                //閉じる
                zf.Close();

                //一時的に書きだしたファイルを消去する。
                try
                {
                    System.IO.File.Delete(file);
                    System.IO.File.Delete(file2);
                }
                catch { }
                try
                {
                    string zipPath2 = System.IO.Path.GetDirectoryName(zipPath) + objBGM.GetComponent <BGMManager>().folderChar + GameObject.Find("ScenarioNameInput").GetComponent <InputField>().text + ".zip";
                    System.IO.File.Move(zipPath, zipPath2);
                    PlayerPrefs.SetString("進行中シナリオ", zipPath2);
                }
                catch
                {
                    GameObject.Find("Error").GetComponent <Text>().text = "同名シナリオがフォルダ内に既にある、もしくは元ファイルが見当たりません";
                    AudioSource bgm = GameObject.Find("BGMManager").GetComponent <AudioSource>(); bgm.loop = false; bgm.clip = errorSE; bgm.Play();
                    StartCoroutine(ErrorWait());
                }
                latitude = Convert.ToDouble(inputField[12].text); longitude = Convert.ToDouble(inputField[13].text);
                MakePasswordFile();
                str3 = "";
                for (int i = 0; i < mapData.Count; i++)
                {
                    if (mapData[i].Replace("\n", "").Replace("\r", "") == "")
                    {
                        continue;
                    }
                    str3 = str3 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n";
                }
                undoList.Add(str3);
                undoListNum = undoList.Count - 1;
            }
            else
            {
                GameObject.Find("Error").GetComponent <Text>().text = "イベントが選択されていません。";
                AudioSource bgm = GameObject.Find("BGMManager").GetComponent <AudioSource>(); bgm.loop = false; bgm.clip = errorSE; bgm.Play();
                StartCoroutine(ErrorWait());
            }
            try { GetMap(); } catch { }
        }
        catch { }
    }
Esempio n. 55
0
    public void SetIvent()
    {
        string[] strs;
        string   passtmp = "";

        try
        {
            if (selectNum > 0)
            {
                FirstPlace.SetActive(false);
                IventMake.SetActive(true);
                strs = mapData[selectNum].Replace("\r", "").Replace("\n", "").Split(',');
                if (strs[10].Contains(" [system]任意イベント"))
                {
                    PLIventToggle.GetComponent <Toggle>().isOn = true; strs[10] = strs[10].Replace(" [system]任意イベント", "");
                }
                else
                {
                    PLIventToggle.GetComponent <Toggle>().isOn = false;
                }
                inputField[0].text  = strs[11].Substring(0, strs[11].Length - 4).Replace("[system]", "");
                inputField[1].text  = strs[0];
                inputField[2].text  = strs[1];
                inputField[3].text  = strs[2];
                inputField[4].text  = strs[3];
                inputField[5].text  = strs[4];
                inputField[6].text  = strs[5];
                inputField[7].text  = strs[6];
                inputField[8].text  = strs[7];
                inputField[9].text  = strs[8];
                inputField[10].text = strs[9];
                inputField[11].text = strs[10];
                latitude            = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
            }
            if (selectNum == 0)
            {
                FirstPlace.SetActive(true);
                IventMake.SetActive(false);
                //閲覧するエントリ
                string extractFile = "[system]command1[system]PC版スタート地点[system].txt";

                //ZipFileオブジェクトの作成
                ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                    new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
                zf.Password = Secret.SecretString.zipPass;
                //展開するエントリを探す
                ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

                if (ze != null)
                {
                    //閲覧するZIPエントリのStreamを取得
                    System.IO.Stream reader = zf.GetInputStream(ze);
                    //文字コードを指定してStreamReaderを作成
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        reader, System.Text.Encoding.GetEncoding("UTF-8"));
                    // テキストを取り出す
                    string text = sr.ReadToEnd();

                    // 読み込んだ目次テキストファイルからstring配列を作成する
                    strs = text.Split('\n');
                    strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
                    //閉じる
                    sr.Close();
                    reader.Close();
                    mapData[selectNum] = ",,,,,,,,,,,[system]PC版スタート地点[system].txt";
                }
                else
                {
                    strs               = new string[2];
                    strs[0]            = "35.010348"; strs[1] = "135.768738";
                    mapData[selectNum] = ",,,,,,,,,,,[system]PC版スタート地点[system].txt";
                }

                ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 = zf.GetEntry("[system]password[system].txt");
                if (ze2 != null)
                {
                    //閲覧するZIPエントリのStreamを取得
                    System.IO.Stream reader = zf.GetInputStream(ze2);
                    //文字コードを指定してStreamReaderを作成
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        reader, System.Text.Encoding.GetEncoding("UTF-8"));
                    // テキストを取り出す
                    passtmp = sr.ReadToEnd();

                    //閉じる
                    sr.Close();
                    reader.Close();
                }

                //閉じる
                zf.Close();
                GameObject.Find("ScenarioNameInput").GetComponent <InputField>().text = System.IO.Path.GetFileNameWithoutExtension(PlayerPrefs.GetString("進行中シナリオ", ""));
                GameObject.Find("PassWordInput").GetComponent <InputField>().text     = passtmp;
                inputField[12].text = strs[0];
                inputField[13].text = strs[1];
                latitude            = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
            }
        }
        catch
        {
        }
    }
Esempio n. 56
0
    //目次ファイルを読み込む。
    private void LoadMapData(string path)
    {
        string str2;

        //string[] strs;
        try
        {
            //閲覧するエントリ
            string extractFile = path;

            //ZipFileオブジェクトの作成
            ICSharpCode.SharpZipLib.Zip.ZipFile zf =
                new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
            zf.Password = Secret.SecretString.zipPass;
            //展開するエントリを探す
            ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(extractFile);

            try
            {
                if (ze != null)
                {
                    //閲覧するZIPエントリのStreamを取得
                    System.IO.Stream reader = zf.GetInputStream(ze);
                    //文字コードを指定してStreamReaderを作成
                    System.IO.StreamReader sr = new System.IO.StreamReader(
                        reader, System.Text.Encoding.GetEncoding("UTF-8"));
                    // テキストを取り出す
                    string text = sr.ReadToEnd();

                    // 読み込んだ目次テキストファイルからstring配列を作成する
                    mapData.AddRange(text.Split('\n'));
                    //閉じる
                    sr.Close();
                    reader.Close();
                    mapData.RemoveAt(mapData.Count - 1);//最終行は[END]なので除去。
                    //イベントをボタンとして一覧に放り込む。
                    for (int i = 0; i < mapData.Count; i++)
                    {
                        objIB.Add(Instantiate(objIvent) as GameObject);
                        objIB[i].transform.SetParent(parentObject.transform, false);
                        objIB[i].GetComponentInChildren <Text>().text   = MapDataToButton(mapData[i]);
                        objIB[i].GetComponent <IventButton>().buttonNum = i;
                        ScenarioFileCheck(i, zf);
                    }
                }
                else
                {
                    GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "TitleScene");
                }
            }
            catch { }

            ze = zf.GetEntry("[system]command1[system]PC版スタート地点[system].txt");

            /*
             * try
             * {
             * if (ze != null)
             * {
             *  //閲覧するZIPエントリのStreamを取得
             *  System.IO.Stream reader = zf.GetInputStream(ze);
             *  //文字コードを指定してStreamReaderを作成
             *  System.IO.StreamReader sr = new System.IO.StreamReader(
             *      reader, System.Text.Encoding.GetEncoding("UTF-8"));
             *  // テキストを取り出す
             *  string text = sr.ReadToEnd();
             *
             *  // 読み込んだ目次テキストファイルからstring配列を作成する
             *  strs = text.Split('\n');
             *  strs = strs[1].Substring(12).Replace("\r", "").Replace("\n", "").Split(',');
             *  //閉じる
             *  sr.Close();
             *  reader.Close();
             *  latitude = Convert.ToDouble(strs[0]); longitude = Convert.ToDouble(strs[1]);
             *  objIB[0].GetComponentInChildren<Text>().text = "PC版スタート地点 緯:" + latitude.ToString() + ",経:" + longitude.ToString();
             * }
             * }
             * catch { }
             */

            //閉じる
            zf.Close();

            str2 = "";
            for (int i = 0; i < mapData.Count; i++)
            {
                if (mapData[i].Replace("\n", "").Replace("\r", "") == "")
                {
                    continue;
                }
                str2 = str2 + mapData[i].Replace("\n", "").Replace("\r", "") + "\r\n";
            }
            undoList.Add(str2);
            undoListNum = undoList.Count - 1;
        }
        catch
        {
            GetComponent <Utility>().StartCoroutine("LoadSceneCoroutine", "TitleScene");
        }
    }
Esempio n. 57
0
        public static void ExtractZipFileToFile(string zipArchiveFilenameIn, string password, string archivedFile, string outFile)
        {
            ZipFile zf = null;
            try
            {
                var fs = File.OpenRead(zipArchiveFilenameIn);
                zf = new ZipFile(fs);
                if (!String.IsNullOrEmpty(password))
                {
                    zf.Password = password;     // AES encrypted entries are handled automatically
                }

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

                    var seperator = Path.DirectorySeparatorChar.ToString(CultureInfo.CurrentUICulture);

                    if (zipEntry.Name.Replace("/", seperator).Equals(archivedFile, StringComparison.InvariantCultureIgnoreCase))
                    {
                        var buffer = new byte[4096]; // 4K is optimum
                        var zipStream = zf.GetInputStream(zipEntry);

                        // Unzip file in buffered chunks. This is just as fast as unpacking to a buffer the full size
                        // of the file, but does not waste memory.
                        // The "using" will close the stream even if an exception occurs.
                        using (var streamWriter = File.Create(outFile))
                        {
                            StreamUtils.Copy(zipStream, streamWriter, buffer);
                        }
                    }
                }
            }
            finally
            {
                if (zf != null)
                {
                    zf.IsStreamOwner = true; // Makes close also shut the underlying stream
                    zf.Close(); // Ensure we release resources
                }
            }
        }
Esempio n. 58
0
    public void PasteButton()
    {
        string str = "";

        string[] strs;
        string   copyfile = "";
        string   file     = @GetComponent <Utility>().GetAppPath() + objBGM.GetComponent <BGMManager>().folderChar + "tmp.txt";

        if (objBGM.GetComponent <BGMManager>().copyMapString == "")
        {
            GameObject.Find("Error").GetComponent <Text>().text = "先にコピー元を選んでください。";
            StartCoroutine(ErrorWait());
            return;
        }
        if (selectNum < 0)
        {
            GameObject.Find("Error").GetComponent <Text>().text = "貼り付け先(そのイベントの後ろに挿入されます)が選択されていません。";
            StartCoroutine(ErrorWait());
            return;
        }
        List <string> strList = new List <string>();

        strList.AddRange(undoList[undoListNum].Replace("\r", "").Split('\n'));

        //コピーするイベント名の取得
        strs = objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n');
        //ZipFileオブジェクトの作成
        ICSharpCode.SharpZipLib.Zip.ZipFile zf =
            new ICSharpCode.SharpZipLib.Zip.ZipFile(PlayerPrefs.GetString("進行中シナリオ", ""));
        zf.Password = Secret.SecretString.zipPass;

        for (int j = 0; j < strs.Length; j++)
        {
            string[] strs2;
            strs2    = strs[j].Split(',');
            copyfile = strs2[11].Replace("\r", "").Replace("\n", "");
            try
            {
                ICSharpCode.SharpZipLib.Zip.ZipEntry ze = zf.GetEntry(copyfile);
                tmpList.Clear();

                //コピーファイルのリスト化
                FileSearchLoop(ze, zf);
                //ファイルのコピー
                for (int i = 0; i < tmpList.Count; i++)
                {
                    ICSharpCode.SharpZipLib.Zip.ZipEntry ze2 = zf.GetEntry(tmpList[i]);
                    if (ze2.Name.Length > 4 && ze2.Name.Substring(ze2.Name.Length - 4) == ".txt")
                    {
                        //閲覧するZIPエントリのStreamを取得
                        System.IO.Stream reader = zf.GetInputStream(ze2);
                        //文字コードを指定してStreamReaderを作成
                        System.IO.StreamReader sr = new System.IO.StreamReader(
                            reader, System.Text.Encoding.GetEncoding("UTF-8"));
                        // テキストを取り出す
                        string text = sr.ReadToEnd();
                        for (int k = 0; k < 9999; k++)
                        {
                            for (int x = 0; x < strList.Count; x++)
                            {
                                if (strList[x].Contains(copyfile.Substring(0, copyfile.Length - 4) + "copy" + k.ToString() + ".txt"))
                                {
                                    break;
                                }
                                if (x == strList.Count - 1)
                                {
                                    copynum = k; goto e1;
                                }
                            }
                        }
e1:
                        text = text.Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt");
                        System.IO.File.WriteAllText(file, text);
                        //ZIP内のエントリの名前を決定する
                        string f = "dammyfile.txt";
                        f = System.IO.Path.GetFileName(tmpList[i].Replace(copyfile, copyfile.Substring(0, copyfile.Length - 4) + "copy" + copynum.ToString() + ".txt"));
                        //ZipFileの更新を開始
                        zf.BeginUpdate();
                        //ZIP書庫に一時的に書きだしておいたファイルを追加する
                        zf.Add(file, f);
                        //ZipFileの更新をコミット
                        zf.CommitUpdate();
                    }
                }
            }
            catch
            {
            }
        }
        //一時的に書きだしたtmp.txtを消去する。
        System.IO.File.Delete(file);

        strList.InsertRange(selectNum + 1, CopyMake(objBGM.GetComponent <BGMManager>().copyMapString.Replace("\r", "").Split('\n'), strList));
        mapData.Clear();
        for (int i = 0; i < objIB.Count; i++)
        {
            Destroy(objIB[i]);
        }
        objIB.Clear();
        // 読み込んだ目次テキストファイルからstring配列を作成する
        mapData.AddRange(strList);
        mapData.RemoveAt(mapData.Count - 1); //最後の行は空白なので消す
                                             //コマンドをボタンとして一覧に放り込む。

        for (int i = 0; i < mapData.Count; i++)
        {
            objIB.Add(Instantiate(objIvent) as GameObject);
            objIB[i].transform.SetParent(parentObject.transform, false);
            objIB[i].GetComponentInChildren <Text>().text   = MapDataToButton(mapData[i]);
            objIB[i].GetComponent <IventButton>().buttonNum = i;

            ScenarioFileCheck(i, zf);
        }
        zf.Close();
        for (int i = 0; i < mapData.Count; i++)
        {
            str = str + mapData[i].Replace("\r", "").Replace("\n", "") + "\r\n";
        }
        undoList.Add(str);
        undoListNum = undoList.Count - 1;
        selectNum   = -1;
        multiSelect.Clear();
        MakeMapDataFile();
    }