コード例 #1
0
ファイル: ZipPackageReader.cs プロジェクト: smther/FreeOQ
		public override Package Read()
		{
			Package package = new Package();
			package.Name = this.packageName;
			ZipInputStream zipInputStream = new ZipInputStream(this.input);
			ZipEntry nextEntry;
			while ((nextEntry = zipInputStream.GetNextEntry()) != null)
			{
				if (!nextEntry.IsDirectory)
				{
					byte[] numArray = new byte[nextEntry.Size];
					int offset = 0;
					int length = numArray.Length;
					int num;
					do
					{
						num = ((Stream)zipInputStream).Read(numArray, offset, length);
						offset += num;
						length -= num;
					}
					while (num > 0);
					string path = nextEntry.Name.Replace('/', '\\').Trim(new char[]	{ '\\' });
					this.AddEntry(package, path, numArray);
				}
			}
			return package;
		}
コード例 #2
0
  public static string[] getFiles( string zipFilename, string folderPath )
  {
    List<string> fileList = new List<string>();

    using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename)))
    {
      ZipEntry entry;
      while ((entry = inputStream.GetNextEntry()) != null)
      {
        if ( entry.FileName.StartsWith( folderPath ) && !entry.IsDirectory )
        {
          char[] charsToTrim = { '/' };
          string entryFilename = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim );
          //Message.Log("entryFilename: '" + entryFilename + "'" );

          //  Must not be a nested file in a subdirectory.
          int idx = entryFilename.LastIndexOf( "/" );
          if ( idx < 0 )
          {
            fileList.Add(entryFilename);
          }
        }
      }
    }

    return fileList.ToArray();
  }
コード例 #3
0
ファイル: UploadFile.aspx.cs プロジェクト: rossspoon/bvcms
 public static void UnZipFiles(string zipPathAndFile, string outputFolder)
 {
     var s = new ZipInputStream(File.OpenRead(zipPathAndFile));
     ZipEntry theEntry;
     var tmpEntry = String.Empty;
     while ((theEntry = s.GetNextEntry()) != null)
     {
         var directoryName = outputFolder;
         var fileName = Path.GetFileName(theEntry.Name);
         if (directoryName != "")
             Directory.CreateDirectory(directoryName);
         if (fileName != String.Empty)
             if (theEntry.Name.IndexOf(".ini") < 0)
             {
                 var fullPath = directoryName + "\\" + theEntry.Name;
                 fullPath = fullPath.Replace("\\ ", "\\");
                 string fullDirPath = Path.GetDirectoryName(fullPath);
                 if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath);
                 FileStream streamWriter = File.Create(fullPath);
                 int size = 2048;
                 byte[] data = new byte[2048];
                 while (true)
                 {
                     size = s.Read(data, 0, data.Length);
                     if (size > 0)
                         streamWriter.Write(data, 0, size);
                     else
                         break;
                 }
                 streamWriter.Close();
             }
     }
     s.Close();
     File.Delete(zipPathAndFile);
 }
コード例 #4
0
ファイル: Archiver.cs プロジェクト: Yitzchok/PublicDomain
        /// <summary>
        /// Reads the zip stream.
        /// </summary>
        /// <param name="jInputStream">The j input stream.</param>
        /// <param name="callback">The callback.</param>
        /// <param name="rock">The rock.</param>
        public static void ReadZipStream(java.io.InputStream jInputStream, CallbackZip callback, object rock)
        {
            ZipInputStream zis = null;
            try
            {
                zis = new ZipInputStream(jInputStream);

                ZipEntry entry;
                ZipEntryE extendedEntry;
                while ((entry = zis.getNextEntry()) != null)
                {
                    extendedEntry = new ZipEntryE(entry);
                    callback(extendedEntry, new ZipEntryInputStream(zis), rock);

                    // Close the entry that we read
                    zis.closeEntry();
                }
            }
            finally
            {
                if (zis != null)
                {
                    zis.close();
                }
            }
        }
コード例 #5
0
  public static void unzipFolder( string zipFilename, string folderPath, string dstFolder )
  {
    byte[] data = new byte[4096];

    using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename)))
    {
      ZipEntry entry;
      while ((entry = inputStream.GetNextEntry()) != null)
      {
        if ( entry.FileName.StartsWith( folderPath ) && !entry.IsDirectory )
        {
          char[] charsToTrim = { '/' };
          string entryName = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim );
          string entryFilename = entryName;
          string entryFolder = dstFolder;

          int idx = entryFilename.LastIndexOf( "/" );
          if ( idx >= 0 )
          {
            entryFolder = dstFolder + "/" + entryFilename.Substring( 0, idx );
            entryFilename = entryFilename.Substring( idx+1 );
          }

          DirectoryInfo dirInfo = new DirectoryInfo(entryFolder);
          if ( !dirInfo.Exists )
          {
            Directory.CreateDirectory( entryFolder );
          }

          Message.Log( "Copying file to '" + entryFolder + "/" + entryFilename + "'" );
          FileStream outputStream = new FileStream( entryFolder + "/" + entryFilename, FileMode.Create, FileAccess.Write );

          int size = inputStream.Read( data, 0, data.Length );
          while ( size > 0 )
          {
            outputStream.Write( data, 0, size );
            size = inputStream.Read( data, 0, data.Length );
          }

          outputStream.Close();
        }
      }
    }
  }
コード例 #6
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        private ISerializable UnZipZeroLength(byte[] zipped)
        {
            if (zipped == null)
            {
                return null;
            }

            object result = null;
            var formatter = new XmlFormatter();
            var memStream = new MemoryStream(zipped);
            using (var zipStream = new ZipInputStream(memStream))
            {
                var zipEntry = zipStream.GetNextEntry();
                if (zipEntry != null)
                {
                    result = formatter.Deserialize(zipStream);
                }
                zipStream.Close();
            }
            memStream.Close();

            return (ISerializable)result;
        }
コード例 #7
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void InvalidPasswordSeekable()
        {
            byte[] originalData = null;
            var compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated, 3, 500, "Hola", true);

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            var buf2 = new byte[originalData.Length];
            var pos = 0;

            var inStream = new ZipInputStream(ms);
            inStream.Password = "******";

            var entry2 = inStream.GetNextEntry();

            while (true)
            {
                var numRead = inStream.Read(buf2, pos, buf2.Length);
                if (numRead <= 0)
                {
                    break;
                }
                pos += numRead;
            }
        }
コード例 #8
0
        private void analyzeFile(string filePath, string fileName)
        {
            //解压文件
            ZipInputStream s = new ZipInputStream(File.OpenRead(filePath + "\\" + fileName));
            ZipEntry       theEntry;

            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(filePath);
                fileName = Path.GetFileName(theEntry.Name);

                //生成解压目录
                Directory.CreateDirectory(directoryName);

                if (fileName != String.Empty)
                {
                    //解压文件到指定的目录
                    FileStream streamWriter = File.Create(filePath + theEntry.Name);

                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            s.Close();

            //遍历解压之后目录下的所有文件,对流水文件分析
            foreach (string file in Directory.GetFiles(filePath))
            {
                fileName = file.Substring(filePath.Length);
                List <Dictionary <int, string> > list = null;

                if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 3) == "ZM_")
                {
                    list = parseZMFile(file);
                }
                else if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 4) == "ZME_")
                {
                    list = parseZMEFile(file);
                }

                if (list != null)
                {
                    Response.Write(fileName + "部分参数读取(读取方式请参考Form_7_2_FileTransfer的代码):<br>\n");
                    Response.Write("<table border='1'>\n");
                    Response.Write("<tr><th>txnType</th><th>orderId</th><th>txnTime(MMDDhhmmss)</th></tr>");
                    foreach (Dictionary <int, string> dic in list)
                    {
                        //TODO 参看https://open.unionpay.com/ajweb/help?id=258,根据编号获取即可,例如订单号12、交易类型20。
                        //具体写代码时可能边读文件边修改数据库性能会更好,请注意自行根据parseFile中的读取方法修改。
                        Response.Write("<tr>\n");
                        Response.Write("<td>" + dic[20] + "</td>\n"); //txnType
                        Response.Write("<td>" + dic[12] + "</td>\n"); //orderId
                        Response.Write("<td>" + dic[5] + "</td>\n");  //txnTime不带年份
                        Response.Write("</tr>\n");
                    }
                    Response.Write("</table>\n");
                }
            }
        }
コード例 #9
0
        public async Task DownloadModuleAsync(string moduleName, string outputFolder, string version, string gitHubAbpLocalRepositoryPath, string gitHubVoloLocalRepositoryPath, AbpCommandLineOptions options)
        {
            Logger.LogInformation("Downloading source code of " + moduleName);
            Logger.LogInformation("Version: " + (version ?? "Latest"));
            Logger.LogInformation("Output folder: " + outputFolder);

            var result = await ModuleProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    SolutionName.Parse(moduleName),
                    moduleName,
                    version,
                    outputFolder,
                    DatabaseProvider.NotSpecified,
                    DatabaseManagementSystem.NotSpecified,
                    UiFramework.NotSpecified,
                    null,
                    false,
                    gitHubAbpLocalRepositoryPath,
                    gitHubVoloLocalRepositoryPath,
                    null,
                    options
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        if (IsAngularTestFile(zipEntry.Name))
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

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

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{moduleName}' has been successfully downloaded to '{outputFolder}'");
        }
コード例 #10
0
		public static bool isZip(System.IO.Stream in_Renamed)
		{
			try
			{
				//UPGRADE_ISSUE: Class 'java.util.zip.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				//UPGRADE_ISSUE: Constructor 'java.util.zip.ZipInputStream.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				ZipInputStream swcZipInputStream = new ZipInputStream(in_Renamed);
				//UPGRADE_ISSUE: Method 'java.util.zip.ZipInputStream.getNextEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				swcZipInputStream.getNextEntry();
				return true;
			}
			catch (System.IO.IOException e)
			{
				return false;
			}
		}
コード例 #11
0
        /// <summary>
        /// Analyze the specified ZIP file for embedded files and directories. Create albums and media objects from the
        /// files. Skip any files whose type is not enabled within Gallery Server Pro. Return a list of skipped files
        /// and the reason why they were skipped.
        /// </summary>
        /// <param name="fileStream">A stream representing a ZIP file containing directories and files to be extracted
        /// to the Gallery Server Pro library.</param>
        /// <param name="parentAlbum">The album that should contain the top-level directories and files found in the ZIP
        /// file.</param>
        /// <param name="discardOriginalImage">Indicates whether to delete the original image file after the thumbnail/
        /// original images have been created. Ignored for non-image files.</param>
        /// <returns>
        /// Returns a <see cref="System.Collections.Generic.List{T}"/> where the key is the name
        /// of the skipped file and the value is the reason for the file being skipped.
        /// </returns>
        public List<ActionResult> ExtractZipFile(Stream fileStream, IAlbum parentAlbum, bool discardOriginalImage)
        {
            if (String.IsNullOrEmpty(this._userName))
                throw new InvalidOperationException("A username was not specified in the ZipUtility constructor. Media objects extracted from a ZIP archive must be associated with a logged on user.");

            this._albumAndDirectoryNamesLookupTable = new Hashtable(10);

            try
            {
                this._zipStream = new ZipInputStream(fileStream);
                this._discardOriginalImage = discardOriginalImage;
                ZipEntry zipContentFile;
                while ((zipContentFile = this._zipStream.GetNextEntry()) != null)
                {
                    IAlbum album = VerifyAlbumExistsAndReturnReference(zipContentFile, parentAlbum);

                    if (Path.GetExtension(zipContentFile.Name).Equals(".zip", StringComparison.OrdinalIgnoreCase))
                    {
                        // We have a ZIP file embedded within the parent zip file. Recursively extract the contents of this file.
                        ExtractEmbeddedZipFile(zipContentFile, parentAlbum);
                    }
                    else
                    {
                        AddMediaObjectToGallery(zipContentFile, album);
                    }
                }
            }
            finally
            {
                this._zipStream.Close();
                this._zipStream = null;

                // Clear the list of hash keys to to ensure a fresh load from the database the next time they are requested.
                MediaObjectHashKeys.Clear();
            }

            return this._fileExtractionResults;
        }
コード例 #12
0
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        /// <param name="fileToUnZip">待解压的文件</param>
        /// <param name="zipedFolder">指定解压目标目录</param>
        /// <param name="password">密码</param>
        /// <returns>解压结果</returns>
        public static bool UnZip(string fileToUnZip, string zipedFolder, string password)
        {
            string         fileName;
            bool           result    = true;
            ZipEntry       ent       = null;
            FileStream     fs        = null;
            ZipInputStream zipStream = null;

            if (!File.Exists(fileToUnZip))
            {
                return(false);
            }

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

            try
            {
                zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
                if (!string.IsNullOrEmpty(password))
                {
                    zipStream.Password = password;
                }

                while ((ent = zipStream.GetNextEntry()) != null)
                {
                    if (!string.IsNullOrEmpty(ent.Name))
                    {
                        fileName = Path.Combine(zipedFolder, ent.Name);
                        //change by Mr.HopeGi
                        fileName = fileName.Replace('/', '\\');

                        int index = ent.Name.LastIndexOf('/');
                        if (index != -1 || fileName.EndsWith("\\"))
                        {
                            string tmpDir = (index != -1 ? fileName.Substring(0, fileName.LastIndexOf('\\')) : fileName) + "\\";
                            if (!Directory.Exists(tmpDir))
                            {
                                Directory.CreateDirectory(tmpDir);
                            }
                            if (tmpDir == fileName)
                            {
                                continue;
                            }
                        }

                        int size = 2048;
                        fs = File.Create(fileName);
                        byte[] data = new byte[size];
                        while (true)
                        {
                            size = zipStream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                fs.Write(data, 0, data.Length);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (zipStream != null)
                {
                    zipStream.Close();
                    zipStream.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }

            return(result);
        }
コード例 #13
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void EmptyZipEntries()
        {
            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            for (var i = 0; i < 10; ++i)
            {
                outStream.PutNextEntry(new ZipEntry(i.ToString()));
            }
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);

            var extractCount = 0;
            ZipEntry entry;
            var decompressedData = new byte[100];

            while ((entry = inStream.GetNextEntry()) != null)
            {
                while (true)
                {
                    var numRead = inStream.Read(decompressedData, extractCount, decompressedData.Length);
                    if (numRead <= 0)
                    {
                        break;
                    }
                    extractCount += numRead;
                }
            }
            inStream.Close();
            Assert.AreEqual(extractCount, 0, "No data should be read from empty entries");
        }
コード例 #14
0
        /// <summary>
        /// 解压功能(解压压缩文件到指定目录)
        /// </summary>
        public void UnZip()
        {
            string FileToUpZip = UpdateModel.UpdateFilePath;
            string ZipedFolder = Application.StartupPath;
            string Password    = "";

            //如果文件不存在就return
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            //如果目录不创建则创建
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }

            ZipInputStream s        = null;
            ZipEntry       theEntry = null;

            string     fileName;
            FileStream streamWriter = null;

            try
            {
                FileStream fs = File.OpenRead(FileToUpZip);
                this.Invoke((UpdatePgBar) delegate(int value) { pgBarUnZip.Maximum = value; }, (int)fs.Length / 1024);
                s          = new ZipInputStream(fs);
                s.Password = Password;
                long count = 0;//计算已解压的文件总大小
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        ///判断文件路径是否是文件夹
                        if (fileName.EndsWith("/") || fileName.EndsWith("//"))
                        {
                            Directory.CreateDirectory(fileName);
                            this.Invoke((AddLogDelegate) delegate(string text) { AddLog(text); }, "正在创建文件夹:" + theEntry.Name);
                            continue;
                        }
                        this.Invoke((AddLogDelegate) delegate(string text) { AddLog(text); }, "正在解压文件:" + theEntry.Name);
                        streamWriter = File.Create(fileName);
                        int    size = 102400;
                        byte[] data = new byte[102400];
                        while (true)
                        {
                            size   = s.Read(data, 0, data.Length);
                            count += size;
                            this.Invoke((UpdatePgBar) delegate(int value)
                            {
                                if (value < pgBarUnZip.Maximum)
                                {
                                    pgBarUnZip.Value = value;
                                }
                            }, (Int32)count / 1024);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            //解压完成 进行下一步 退出更新程序或者执行脚本
            if (!string.IsNullOrEmpty(UpdateModel.ScriptUrl))
            {
                this.Invoke((UpdatePgBar) delegate(int value)
                {
                    FrmCmd frmCmd = new FrmCmd();
                    frmCmd.Show();
                    this.Hide();
                }, 0);
            }
            else
            {
                DirectoryInfo directoryInfo = new DirectoryInfo("Update");
                directoryInfo.Delete(true);
                Process.Start(UpdateModel.Start + ".exe");
                Environment.Exit(0);
            }
        }
コード例 #15
0
        private static void LoadDLLs(bool plugins = false)
        {
            string searchdir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, (plugins ? "Plugins" : "Mods"));

            if (!Directory.Exists(searchdir))
            {
                Directory.CreateDirectory(searchdir);
            }
            else
            {
                // DLL
                string[] files = Directory.GetFiles(searchdir, "*.dll");
                if (files.Length > 0)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        string file = files[i];
                        if (!string.IsNullOrEmpty(file))
                        {
                            if (plugins)
                            {
                                if ((Imports.IsDevPluginsOnly() && !file.EndsWith("-dev.dll")) || (!Imports.IsDevPluginsOnly() && file.EndsWith("-dev.dll")))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                if ((Imports.IsDevModsOnly() && !file.EndsWith("-dev.dll")) || (!Imports.IsDevModsOnly() && file.EndsWith("-dev.dll")))
                                {
                                    continue;
                                }
                            }
                            try
                            {
                                LoadAssembly(File.ReadAllBytes(file), plugins, file);
                            }
                            catch (Exception e)
                            {
                                MelonModLogger.LogError("Unable to load " + file + ":\n" + e.ToString());
                                MelonModLogger.Log("------------------------------");
                            }
                        }
                    }
                }

                // ZIP
                string[] zippedFiles = Directory.GetFiles(searchdir, "*.zip");
                if (zippedFiles.Length > 0)
                {
                    for (int i = 0; i < zippedFiles.Length; i++)
                    {
                        string file = zippedFiles[i];
                        if (!string.IsNullOrEmpty(file))
                        {
                            try
                            {
                                using (var fileStream = File.OpenRead(file))
                                {
                                    using (var zipInputStream = new ZipInputStream(fileStream))
                                    {
                                        ZipEntry entry;
                                        while ((entry = zipInputStream.GetNextEntry()) != null)
                                        {
                                            string filename = Path.GetFileName(entry.Name);
                                            if (string.IsNullOrEmpty(filename) || !filename.EndsWith(".dll"))
                                            {
                                                continue;
                                            }

                                            if (plugins)
                                            {
                                                if ((Imports.IsDevPluginsOnly() && !filename.EndsWith("-dev.dll")) || (!Imports.IsDevPluginsOnly() && filename.EndsWith("-dev.dll")))
                                                {
                                                    continue;
                                                }
                                            }
                                            else
                                            {
                                                if ((Imports.IsDevModsOnly() && !filename.EndsWith("-dev.dll")) || (!Imports.IsDevModsOnly() && filename.EndsWith("-dev.dll")))
                                                {
                                                    continue;
                                                }
                                            }

                                            using (var unzippedFileStream = new MemoryStream())
                                            {
                                                int    size   = 0;
                                                byte[] buffer = new byte[4096];
                                                while (true)
                                                {
                                                    size = zipInputStream.Read(buffer, 0, buffer.Length);
                                                    if (size > 0)
                                                    {
                                                        unzippedFileStream.Write(buffer, 0, size);
                                                    }
                                                    else
                                                    {
                                                        break;
                                                    }
                                                }
                                                LoadAssembly(unzippedFileStream.ToArray(), plugins, (file + "/" + filename));
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                MelonModLogger.LogError("Unable to load " + file + ":\n" + e.ToString());
                                MelonModLogger.Log("------------------------------");
                            }
                        }
                    }
                }
            }
        }
コード例 #16
0
        private void UnpackApkAssets(string apkPath)
        {
            if (!File.Exists(apkPath))
            {
                return;
            }

            string destDirRoot = Path.GetDirectoryName(apkPath);

            destDirRoot += "/" + Path.GetFileNameWithoutExtension(apkPath) + "_gplay/";
            if (Directory.Exists(destDirRoot))
            {
                Directory.Delete(destDirRoot, true);
            }
            Directory.CreateDirectory(destDirRoot);

            try
            {
                List <string> lstSplit0Files = new List <string>();
                using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(apkPath)))
                {
                    ZipEntry theEntry;
                    label_result.Text = string.Empty;

                    //List<string> lstMergeFilePaths = new List<string>();
                    while ((theEntry = zipInputStream.GetNextEntry()) != null)
                    {
                        string filePath = theEntry.Name;

                        if (!filePath.StartsWith("assets/"))
                        {
                            continue;
                        }

                        string relativeDirName = Path.GetDirectoryName(filePath);
                        string fileName        = Path.GetFileName(filePath);

                        string fileDir = destDirRoot + relativeDirName + "/";

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

                        bool   isNeedZip    = false;
                        string destFileName = fileName;

                        Regex regex = new Regex(".split0$");
                        if (regex.IsMatch(destFileName))
                        {
                            lstSplit0Files.Add(filePath);
                            //destFileName = regex.Replace(destFileName, "");
                            //string mergeFilePath = fileDir + destFileName;
                            //if (!lstMergeFilePaths.Contains(mergeFilePath))
                            //    lstMergeFilePaths.Add(mergeFilePath);
                        }
                        //else
                        if (relativeDirName != "assets" && !filePath.Equals("assets/bin/Data/settings.xml", StringComparison.OrdinalIgnoreCase))
                        {
                            isNeedZip     = true;
                            destFileName += ".obb";
                        }

                        if (isNeedZip)
                        {
                            ZipStreamToObb(zipInputStream, fileDir + destFileName, fileName);
                        }
                        else
                        {
                            using (FileStream fileStream = File.Open(fileDir + destFileName, FileMode.OpenOrCreate))
                            {
                                fileStream.Seek(0, SeekOrigin.End);
                                PipeStream(zipInputStream, fileStream);
                            }
                        }
                    }

                    //foreach (string mergeFilePath in lstMergeFilePaths)
                    //{
                    //    string zipMergeFilePath = mergeFilePath + ".obb";
                    //    using (FileStream fileStream = File.Open(mergeFilePath, FileMode.Open))
                    //    {
                    //        ZipStreamToObb(fileStream, zipMergeFilePath, Path.GetFileName(mergeFilePath));
                    //    }
                    //    File.Delete(mergeFilePath);
                    //}
                }
                AddSplit0InGlobalPackage(destDirRoot, lstSplit0Files);
            }
            catch (Exception e)
            {
                label_result.Text = e.ToString();
            }
        }
コード例 #17
0
        public static void ParsePackage(string file, string installPath, Dictionary <string, PackageInfo> packages, List <string> invalidPackages)
        {
            Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            var    unzip       = new ZipInputStream(inputStream);

            try
            {
                ZipEntry entry = unzip.GetNextEntry();

                while (entry != null)
                {
                    if (!entry.IsDirectory)
                    {
                        var    fileName  = entry.Name;
                        string extension = Path.GetExtension(fileName);
                        if (extension != null && (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5"))
                        {
                            //Manifest
                            var manifestReader = new StreamReader(unzip);
                            var manifest       = manifestReader.ReadToEnd();

                            var package = new PackageInfo {
                                Manifest = manifest
                            };
                            if (!string.IsNullOrEmpty(manifest))
                            {
                                var            doc         = new XPathDocument(new StringReader(manifest));
                                XPathNavigator rootNav     = doc.CreateNavigator().SelectSingleNode("dotnetnuke");
                                string         packageType = String.Empty;
                                if (rootNav.Name == "dotnetnuke")
                                {
                                    packageType = XmlUtils.GetAttributeValue(rootNav, "type");
                                }
                                else if (rootNav.Name.ToLower() == "languagepack")
                                {
                                    packageType = "LanguagePack";
                                }

                                XPathNavigator nav = null;
                                switch (packageType.ToLower())
                                {
                                case "package":
                                    nav = rootNav.SelectSingleNode("packages/package");
                                    break;

                                case "module":
                                case "languagepack":
                                case "skinobject":
                                    nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package");
                                    break;
                                }

                                if (nav != null)
                                {
                                    package.Name            = XmlUtils.GetAttributeValue(nav, "name");
                                    package.PackageType     = XmlUtils.GetAttributeValue(nav, "type");
                                    package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false);
                                    package.Version         = new Version(XmlUtils.GetAttributeValue(nav, "version"));
                                    package.FriendlyName    = XmlUtils.GetNodeValue(nav, "friendlyName");
                                    if (String.IsNullOrEmpty(package.FriendlyName))
                                    {
                                        package.FriendlyName = package.Name;
                                    }
                                    package.Description = XmlUtils.GetNodeValue(nav, "description");
                                    package.FileName    = file.Replace(installPath + "\\", "");

                                    XPathNavigator foldernameNav;
                                    switch (package.PackageType)
                                    {
                                    case "Module":
                                        //In Dynamics moduels, a component:type=File can have a basePath pointing to the App_Conde folder. This is not a correct FolderName
                                        //To ensure that FolderName is DesktopModules...
                                        var folderNameValue = GetSpecificFolderName(nav, "components/component/files|components/component/resourceFiles", "basePath", "DesktopModules");
                                        if (!String.IsNullOrEmpty(folderNameValue))
                                        {
                                            package.FolderName = folderNameValue.Replace('\\', '/');
                                        }
                                        break;

                                    case "Auth_System":
                                        foldernameNav = nav.SelectSingleNode("components/component/files");
                                        if (foldernameNav != null)
                                        {
                                            package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/');
                                        }
                                        break;

                                    case "Container":
                                        foldernameNav = nav.SelectSingleNode("components/component/containerFiles");
                                        if (foldernameNav != null)
                                        {
                                            package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/');
                                        }
                                        break;

                                    case "Skin":
                                        foldernameNav = nav.SelectSingleNode("components/component/skinFiles");
                                        if (foldernameNav != null)
                                        {
                                            package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/');
                                        }
                                        break;

                                    default:
                                        break;
                                    }

                                    XPathNavigator iconFileNav = nav.SelectSingleNode("iconFile");
                                    if (package.FolderName != string.Empty && iconFileNav != null)
                                    {
                                        if ((iconFileNav.Value != string.Empty) && (package.PackageType == "Module" || package.PackageType == "Auth_System" || package.PackageType == "Container" || package.PackageType == "Skin"))
                                        {
                                            if (iconFileNav.Value.StartsWith("~/"))
                                            {
                                                package.IconFile = iconFileNav.Value;
                                            }
                                            else if (iconFileNav.Value.StartsWith("DesktopModules", StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                package.IconFile = string.Format("~/{0}", iconFileNav.Value);
                                            }
                                            else
                                            {
                                                package.IconFile = (String.IsNullOrEmpty(package.FolderName) ? "" : package.FolderName + "/") + iconFileNav.Value;
                                                package.IconFile = (!package.IconFile.StartsWith("~/")) ? "~/" + package.IconFile : package.IconFile;
                                            }
                                        }
                                    }

                                    //Parse the Dependencies
                                    foreach (XPathNavigator dependencyNav in nav.CreateNavigator().Select("dependencies/dependency"))
                                    {
                                        var dependency       = DependencyFactory.GetDependency(dependencyNav);
                                        var packageDependecy = dependency as IManagedPackageDependency;

                                        if (packageDependecy != null)
                                        {
                                            package.Dependencies.Add(packageDependecy.PackageDependency);
                                        }
                                    }

                                    packages.Add(file, package);
                                }
                            }

                            break;
                        }
                    }
                    entry = unzip.GetNextEntry();
                }
            }
            catch (Exception)
            {
                invalidPackages.Add(file);
            }
            finally
            {
                unzip.Close();
                unzip.Dispose();
            }
        }
コード例 #18
0
        /// <summary>
        /// Deserializes the specified input stream.
        /// </summary>
        /// <param name="inputStream">The input stream.</param>
        /// <exception cref="System.ArgumentNullException">inputStream</exception>
        /// <exception cref="InvalidFormatException">Unable to find the manifest file.</exception>
        protected void Deserialize(Stream inputStream)
        {
            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }

            var isSearchingForManifest = true;

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

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

                            zip.CloseEntry();

                            ManifestDeserialized();

                            CreateArtifactSerializers();

                            FinishLoadingArtifacts(lazyStack, zip);

                            break;
                        }

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

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

                        isSearchingForManifest = false;

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

                        ManifestDeserialized();

                        CreateArtifactSerializers();

                        FinishLoadingArtifacts(zip);


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

            if (!isSearchingForManifest)
            {
                return;
            }

            throw new InvalidFormatException("Unable to find the manifest file.");
        }
コード例 #19
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void PasswordCheckingWithDateInExtraData()
        {
            var ms = new MemoryStream();
            var checkTime = new DateTime(2010, 10, 16, 0, 3, 28);

            using (var zos = new ZipOutputStream(ms))
            {
                zos.IsStreamOwner = false;
                zos.Password = "******";
                var ze = new ZipEntry("uno");
                ze.DateTime = new DateTime(1998, 6, 5, 4, 3, 2);

                var zed = new ZipExtraData();

                zed.StartNewEntry();

                zed.AddData(1);

                var delta = checkTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
                var seconds = (int) delta.TotalSeconds;
                zed.AddLeInt(seconds);
                zed.AddNewEntry(0x5455);

                ze.ExtraData = zed.GetEntryData();
                zos.PutNextEntry(ze);
                zos.WriteByte(54);
            }

            ms.Position = 0;
            using (var zis = new ZipInputStream(ms))
            {
                zis.Password = "******";
                var uno = zis.GetNextEntry();
                var theByte = (byte) zis.ReadByte();
                Assert.AreEqual(54, theByte);
                Assert.AreEqual(-1, zis.ReadByte());
                Assert.AreEqual(checkTime, uno.DateTime);
            }
        }
コード例 #20
0
ファイル: ZipHelper.cs プロジェクト: wengzhilai/OldWebApi
        /// <summary>
        /// 取zip文件中的指定文件
        /// Android *.apk AndroidManifest.xml
        /// iOS *.ipa iTunesMetadata.plist
        /// WP *.* AppManifest.xaml
        /// </summary>
        /// <param name="zipFileName">zip文件</param>
        /// <param name="innerFileName">需要取的文件名</param>
        /// <param name="fuzzySame">模糊比较文件名</param>
        /// <returns></returns>
        public static byte[] ReadInnerFileBytes(string zipFileName, string innerFileName, bool fuzzySame)
        {
            if (!File.Exists(zipFileName))
            {
                return(null);
            }

            innerFileName = innerFileName.ToLower();
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
            {
                ZipEntry entry;//AndroidManifest.xml
                while ((entry = s.GetNextEntry()) != null)
                {
                    string srcName = entry.Name.ToLower();

                    if (entry.Name == innerFileName || fuzzySame && srcName.IndexOf(innerFileName) >= 0)
                    {
                        List <byte> dyns    = null;
                        byte[]      buff    = new byte[10240];
                        bool        isFirst = true;

                        while (true)
                        {
                            int size = s.Read(buff, 0, 10240);
                            if (size > 0)
                            {
                                if (isFirst && size < 10240)
                                {
                                    byte[] rr = new byte[size];
                                    Array.Copy(buff, rr, size);
                                    return(rr);
                                }
                                isFirst = false;
                                if (dyns == null)
                                {
                                    dyns = new List <byte>(10240 * 2);
                                }
                                if (size == 10240)
                                {
                                    dyns.AddRange(buff);
                                }
                                else
                                {
                                    for (int i = 0; i < size; i++)
                                    {
                                        dyns.Add(buff[i]);
                                    }
                                }
                            }
                            else
                            {
                                break;
                            }
                        }

                        return(dyns != null?dyns.ToArray() : null);
                    }
                }
            }
            return(null);
        }
コード例 #21
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void Stream_UnicodeEntries()
        {
            var ms = new MemoryStream();
            using (var s = new ZipOutputStream(ms))
            {
                s.IsStreamOwner = false;

                var sampleName = "\u03A5\u03d5\u03a3";
                var sample = new ZipEntry(sampleName);
                sample.IsUnicodeText = true;
                s.PutNextEntry(sample);

                s.Finish();
                ms.Seek(0, SeekOrigin.Begin);

                using (var zis = new ZipInputStream(ms))
                {
                    var ze = zis.GetNextEntry();
                    Assert.AreEqual(sampleName, ze.Name, "Expected name to match original");
                    Assert.IsTrue(ze.IsUnicodeText, "Expected IsUnicodeText flag to be set");
                }
            }
        }
コード例 #22
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="zipBytes">需解压的文件字节数组</param>
        /// <param name="destDir">目的目录路径</param>
        /// <returns></returns>
        public static string UnZip(byte[] zipBytes, string destDir)
        {
            string rootFile = " ";
            //读取压缩文件(zip文件),准备解压缩
            MemoryStream   ms = new MemoryStream(zipBytes);
            ZipInputStream s  = new ZipInputStream(ms);
            ZipEntry       theEntry;
            string         path = destDir;
            //解压出来的文件保存的路径

            string rootDir = " ";

            //根目录下的第一个子文件夹的名称
            while ((theEntry = s.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(Util.FromBase64String(theEntry.Name));
                //得到根目录下的第一级子文件夹的名称
                if (rootDir.IndexOf("\\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                }
                string dir = Path.GetDirectoryName(Util.FromBase64String(theEntry.Name));
                //根目录下的第一级子文件夹的下的文件夹的名称
                string fileName = Path.GetFileName(Util.FromBase64String(theEntry.Name));
                //根目录下的文件名称
                if (dir != " ")
                //创建根目录下的子文件夹,不限制级别
                {
                    if (!Directory.Exists(destDir + "\\" + dir))
                    {
                        path = destDir + "\\" + dir;
                        //在指定的路径创建文件夹
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")
                //根目录下的文件
                {
                    path     = destDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")
                //根目录下的第一级子文件夹下的文件
                {
                    if (dir.IndexOf("\\") > 0)
                    //指定文件保存的路径
                    {
                        path = destDir + "\\" + dir;
                    }
                }

                if (dir == rootDir)
                //判断是不是需要保存在根目录下的文件
                {
                    path = destDir + "\\" + rootDir;
                }

                //以下为解压缩zip文件的基本步骤
                //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                if (fileName != String.Empty)
                {
                    if (theEntry.Size == 0 && string.Equals(theEntry.Comment, "d"))
                    {
                        Directory.CreateDirectory(path + "\\" + fileName);
                    }
                    else
                    {
                        FileStream streamWriter = File.Create(path + "\\" + fileName);

                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }

                        streamWriter.Close();
                    }
                }
            }
            s.Close();

            return(rootFile);
        }
コード例 #23
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void SingleLargeEntry()
        {
            window_ = new WindowedStream(0x10000);
            outStream_ = new ZipOutputStream(window_);
            inStream_ = new ZipInputStream(window_);

            long target = 0x10000000;
            readTarget_ = writeTarget_ = target;

            var reader = new Thread(Reader);
            reader.Name = "Reader";

            var writer = new Thread(Writer);
            writer.Name = "Writer";

            var startTime = DateTime.Now;
            reader.Start();
            writer.Start();

            writer.Join();
            reader.Join();

            var endTime = DateTime.Now;
            var span = endTime - startTime;
            Console.WriteLine("Time {0} throughput {1} KB/Sec", span, (target/1024)/span.TotalSeconds);
        }
コード例 #24
0
ファイル: InstallFile.cs プロジェクト: AnonDevelopment/cms
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// The ReadZip method reads the zip stream and parses the ZipEntry metadata
 /// </summary>
 /// <param name="unzip">A ZipStream containing the file content</param>
 /// <param name="entry">A ZipEntry containing the file metadata</param>
 /// -----------------------------------------------------------------------------
 private void ReadZip(ZipInputStream unzip, ZipEntry entry)
 {
     ParseFileName(entry.Name);
     Util.WriteStream(unzip, TempFileName);
     File.SetLastWriteTime(TempFileName, entry.DateTime);
 }
コード例 #25
0
ファイル: Themes.cs プロジェクト: noximus/TopOfTheRock
    /// <summary>
    /// UnZip Theme
    /// </summary>
    /// <param name="themesPath"></param>
    /// <param name="fileStream"></param>
    public void UnZip(string themesPath, Stream fileStream)
    {
        ZipInputStream s = new ZipInputStream(fileStream);
        ZipEntry theEntry = null;
        while ((theEntry = s.GetNextEntry()) != null)
        {

            string directoryName = Path.GetDirectoryName(themesPath + theEntry.Name);
            string fileName = Path.GetFileName(theEntry.Name);

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

            if (fileName != String.Empty)
            {
                using (FileStream streamWriter = File.Create(themesPath + theEntry.Name))
                {

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
        s.Close();
    }
コード例 #26
0
ファイル: InstallFile.cs プロジェクト: AnonDevelopment/cms
 /// -----------------------------------------------------------------------------
 /// <summary>
 /// This Constructor creates a new InstallFile instance from a ZipInputStream and a ZipEntry
 /// </summary>
 /// <remarks>The ZipInputStream is read into a byte array (Buffer), and the ZipEntry is used to
 /// set up the properties of the InstallFile class.</remarks>
 /// <param name="zip">The ZipInputStream</param>
 /// <param name="entry">The ZipEntry</param>
 /// <param name="info">An INstallerInfo instance</param>
 /// -----------------------------------------------------------------------------
 public InstallFile(ZipInputStream zip, ZipEntry entry, InstallerInfo info)
 {
     Encoding      = TextEncoding.UTF8;
     InstallerInfo = info;
     ReadZip(zip, entry);
 }
コード例 #27
0
        public void CacheClassBytes(FileInfo jar)
        {
            // experimental..
            try
            {
                Console.WriteLine(".cache: " + jar.FullName);

                var zip = default(ZipInputStream);


                zip = new ZipInputStream(new jvm::java.io.FileInputStream(jar.FullName));


                var Current = zip.getNextEntry();

                while (Current != null)
                {
                    var Name = Current.getName();

                    if (Name.EndsWith(".class"))
                    {
                        var TypeName = Name.Substring(0, Name.Length - ".class".Length).Replace("/", ".");

                        if (TypeName.StartsWith("java."))
                        {
                            // we cannot use ClassLoader to load such class anyhow..
                            // what we probably would need is a JVM parser now...
                        }
                        else
                        {
                            var Memory = zip.ReadToMemoryStream();

                            this.ClassBytes[TypeName] = Memory.ToArray();
                        }
                    }

                    Current = zip.getNextEntry();
                }

            }
            catch (jvm::csharp.ThrowableException cc)
            {
                Console.WriteLine("error @CacheClassBytes: " + cc);

                throw new InvalidOperationException();
            }
        }
コード例 #28
0
ファイル: NewCommand.cs プロジェクト: zjc-china/abp
        public async Task ExecuteAsync(CommandLineArgs commandLineArgs)
        {
            var projectName = NamespaceHelper.NormalizeNamespace(commandLineArgs.Target);

            if (projectName == null)
            {
                throw new CliUsageException(
                          "Project name is missing!" +
                          Environment.NewLine + Environment.NewLine +
                          GetUsageInfo()
                          );
            }

            if (!ProjectNameValidator.IsValid(projectName))
            {
                throw new CliUsageException("The project name is invalid! Please specify a different name.");
            }

            Logger.LogInformation("Creating your project...");
            Logger.LogInformation("Project name: " + projectName);

            var template = commandLineArgs.Options.GetOrNull(Options.Template.Short, Options.Template.Long);

            if (template != null)
            {
                Logger.LogInformation("Template: " + template);
            }
            else
            {
                template = (await TemplateInfoProvider.GetDefaultAsync()).Name;
            }

            var version = commandLineArgs.Options.GetOrNull(Options.Version.Short, Options.Version.Long);

            if (version != null)
            {
                Logger.LogInformation("Version: " + version);
            }

            var isTiered = commandLineArgs.Options.ContainsKey(Options.Tiered.Long);

            if (isTiered)
            {
                Logger.LogInformation("Tiered: yes");
            }

            var preview = commandLineArgs.Options.ContainsKey(Options.Preview.Long);

            if (preview)
            {
                Logger.LogInformation("Preview: yes");
            }

            var databaseProvider = GetDatabaseProvider(commandLineArgs);

            if (databaseProvider != DatabaseProvider.NotSpecified)
            {
                Logger.LogInformation("Database provider: " + databaseProvider);
            }

            var connectionString = GetConnectionString(commandLineArgs);

            if (connectionString != null)
            {
                Logger.LogInformation("Connection string: " + connectionString);
            }

            var databaseManagementSystem = GetDatabaseManagementSystem(commandLineArgs);

            if (databaseManagementSystem != DatabaseManagementSystem.NotSpecified)
            {
                Logger.LogInformation("DBMS: " + databaseManagementSystem);
            }

            var uiFramework = GetUiFramework(commandLineArgs);

            if (uiFramework != UiFramework.NotSpecified)
            {
                Logger.LogInformation("UI Framework: " + uiFramework);
            }

            var publicWebSite = uiFramework != UiFramework.None && commandLineArgs.Options.ContainsKey(Options.PublicWebSite.Long);

            if (publicWebSite)
            {
                Logger.LogInformation("Public Web Site: yes");
            }

            var mobileApp = GetMobilePreference(commandLineArgs);

            if (mobileApp != MobileApp.None)
            {
                Logger.LogInformation("Mobile App: " + mobileApp);
            }

            var gitHubAbpLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubAbpLocalRepositoryPath.Long);

            if (gitHubAbpLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Abp Local Repository Path: " + gitHubAbpLocalRepositoryPath);
            }

            var gitHubVoloLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubVoloLocalRepositoryPath.Long);

            if (gitHubVoloLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Volo Local Repository Path: " + gitHubVoloLocalRepositoryPath);
            }

            var templateSource = commandLineArgs.Options.GetOrNull(Options.TemplateSource.Short, Options.TemplateSource.Long);

            if (templateSource != null)
            {
                Logger.LogInformation("Template Source: " + templateSource);
            }

            var createSolutionFolder = GetCreateSolutionFolderPreference(commandLineArgs);

            var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long);

            var outputFolderRoot =
                outputFolder != null?Path.GetFullPath(outputFolder) : Directory.GetCurrentDirectory();

            SolutionName solutionName;

            if (MicroserviceServiceTemplateBase.IsMicroserviceServiceTemplate(template))
            {
                var microserviceSolutionName = FindMicroserviceSolutionName(outputFolderRoot);

                if (microserviceSolutionName == null)
                {
                    throw new CliUsageException("This command should be run inside a folder that contains a microservice solution!");
                }

                solutionName = SolutionName.Parse(microserviceSolutionName, projectName);
                outputFolder = MicroserviceServiceTemplateBase.CalculateTargetFolder(outputFolderRoot, projectName);
                uiFramework  = uiFramework == UiFramework.NotSpecified ? FindMicroserviceSolutionUiFramework(outputFolderRoot) : uiFramework;
            }
            else
            {
                solutionName = SolutionName.Parse(projectName);

                outputFolder = createSolutionFolder ?
                               Path.Combine(outputFolderRoot, SolutionName.Parse(projectName).FullName) :
                               outputFolderRoot;
            }

            Volo.Abp.IO.DirectoryHelper.CreateIfNotExists(outputFolder);

            Logger.LogInformation("Output folder: " + outputFolder);

            if (connectionString == null &&
                databaseManagementSystem != DatabaseManagementSystem.NotSpecified &&
                databaseManagementSystem != DatabaseManagementSystem.SQLServer)
            {
                connectionString = ConnectionStringProvider.GetByDbms(databaseManagementSystem, outputFolder);
            }

            commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command);

            var result = await TemplateProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    solutionName,
                    template,
                    version,
                    databaseProvider,
                    databaseManagementSystem,
                    uiFramework,
                    mobileApp,
                    publicWebSite,
                    gitHubAbpLocalRepositoryPath,
                    gitHubVoloLocalRepositoryPath,
                    templateSource,
                    commandLineArgs.Options,
                    connectionString
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        if (string.IsNullOrWhiteSpace(zipEntry.Name))
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

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

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{projectName}' has been successfully created to '{outputFolder}'");


            if (AppTemplateBase.IsAppTemplate(template))
            {
                var isCommercial = template == AppProTemplate.TemplateName;
                OpenThanksPage(uiFramework, databaseProvider, isTiered || commandLineArgs.Options.ContainsKey("separate-identity-server"), isCommercial);
            }
            else if (MicroserviceTemplateBase.IsMicroserviceTemplate(template))
            {
                OpenMicroserviceDocumentPage();
            }
        }
コード例 #29
0
ファイル: ZipUtility.cs プロジェクト: haimon74/KanNaim
		/// <summary>
		/// Analyze the specified ZIP file for embedded files and directories. Create albums and media objects from the
		/// files. Skip any files whose type is not enabled within Gallery Server Pro. Return a list of skipped files
		/// and the reason why they were skipped.
		/// </summary>
		/// <param name="fileStream">A stream representing a ZIP file containing directories and files to be extracted
		/// to the Gallery Server Pro library.</param>
		/// <param name="parentAlbum">The album that should contain the top-level directories and files found in the ZIP
		/// file.</param>
		/// <param name="discardOriginalImage">Indicates whether to delete the original image file after the thumbnail/
		/// original images have been created. Ignored for non-image files.</param>
		/// <returns>
		/// Returns a <see cref="System.Collections.Generic.List{T}"/> where the key is the name
		/// of the skipped file and the value is the reason for the file being skipped.
		/// </returns>
		public List<KeyValuePair<string, string>> ExtractZipFile(Stream fileStream, IAlbum parentAlbum, bool discardOriginalImage)
		{
			if (String.IsNullOrEmpty(this._userName))
				throw new InvalidOperationException("A username was not specified in the ZipUtility constructor. Media objects extracted from a ZIP archive must be associated with a logged on user.");
			
			this._albumAndDirectoryNamesLookupTable = new Hashtable(10);

			try
			{
				this._zipStream = new ZipInputStream(fileStream);
				this._discardOriginalImage = discardOriginalImage;
				ZipEntry zipContentFile;
				while ((zipContentFile = this._zipStream.GetNextEntry()) != null)
				{
					IAlbum album = VerifyAlbumExistsAndReturnReference(zipContentFile, parentAlbum);

					if (Path.GetExtension(zipContentFile.Name).ToUpperInvariant() == ".ZIP")
					{
						// We have a ZIP file embedded within the parent zip file. Recursively extract the contents of this file.
						ExtractEmbeddedZipFile(zipContentFile, parentAlbum);
					}
					else
					{
						AddMediaObjectToGallery(zipContentFile, album);
					}
				}
			}
			finally
			{
				this._zipStream.Close();
				this._zipStream = null;

				// Clear the list of hash keys to free up memory.
				MediaObjectHashKeys.Clear();
			}

			return this._skippedFiles;
		}
コード例 #30
0
        private void BindGrid(string installPath, DataGrid grid)
        {
            var packages        = new List <PackageInfo>();
            var invalidPackages = new List <string>();

            foreach (string file in Directory.GetFiles(installPath))
            {
                if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources"))
                {
                    Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                    var    unzip       = new ZipInputStream(inputStream);

                    try
                    {
                        ZipEntry entry = unzip.GetNextEntry();

                        while (entry != null)
                        {
                            if (!entry.IsDirectory)
                            {
                                string fileName  = entry.Name;
                                string extension = Path.GetExtension(fileName);
                                if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5")
                                {
                                    //Manifest
                                    var    manifestReader = new StreamReader(unzip);
                                    string manifest       = manifestReader.ReadToEnd();

                                    var package = new PackageInfo();
                                    package.Manifest = manifest;
                                    if (!string.IsNullOrEmpty(manifest))
                                    {
                                        var            doc         = new XPathDocument(new StringReader(manifest));
                                        XPathNavigator rootNav     = doc.CreateNavigator().SelectSingleNode("dotnetnuke");
                                        string         packageType = String.Empty;
                                        if (rootNav.Name == "dotnetnuke")
                                        {
                                            packageType = XmlUtils.GetAttributeValue(rootNav, "type");
                                        }
                                        else if (rootNav.Name.ToLower() == "languagepack")
                                        {
                                            packageType = "LanguagePack";
                                        }
                                        XPathNavigator nav = null;
                                        switch (packageType.ToLower())
                                        {
                                        case "package":
                                            nav = rootNav.SelectSingleNode("packages/package");
                                            break;

                                        case "languagepack":

                                            nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package");
                                            break;
                                        }

                                        if (nav != null)
                                        {
                                            package.Name            = XmlUtils.GetAttributeValue(nav, "name");
                                            package.PackageType     = XmlUtils.GetAttributeValue(nav, "type");
                                            package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false);
                                            package.Version         = new Version(XmlUtils.GetAttributeValue(nav, "version"));
                                            package.FriendlyName    = XmlUtils.GetNodeValue(nav, "friendlyName");
                                            if (String.IsNullOrEmpty(package.FriendlyName))
                                            {
                                                package.FriendlyName = package.Name;
                                            }
                                            package.Description = XmlUtils.GetNodeValue(nav, "description");
                                            package.FileName    = file.Replace(installPath + "\\", "");

                                            packages.Add(package);
                                        }
                                    }

                                    break;
                                }
                            }
                            entry = unzip.GetNextEntry();
                        }
                    }
                    catch (Exception)
                    {
                        invalidPackages.Add(file);
                    }
                    finally
                    {
                        unzip.Close();
                        unzip.Dispose();
                    }
                }
            }

            //now add language packs from update service
            try
            {
                StreamReader myResponseReader = UpdateService.GetLanguageList();
                var          xmlDoc           = new XmlDocument();
                xmlDoc.Load(myResponseReader);
                XmlNodeList languages = xmlDoc.SelectNodes("available/language");

                if (languages != null)
                {
                    var installedPackages  = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack");
                    var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList();
                    foreach (XmlNode language in languages)
                    {
                        string cultureCode = "";
                        string version     = "";
                        foreach (XmlNode child in language.ChildNodes)
                        {
                            if (child.Name == "culturecode")
                            {
                                cultureCode = child.InnerText;
                            }

                            if (child.Name == "version")
                            {
                                version = child.InnerText;
                            }
                        }
                        if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6)
                        {
                            var myCIintl = new CultureInfo(cultureCode, true);
                            version = version.Insert(4, ".").Insert(2, ".");
                            var package = new PackageInfo {
                                Owner = OwnerUpdateService, Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName
                            };
                            package.Name        = myCIintl.NativeName;
                            package.Description = cultureCode;
                            Version ver = null;
                            Version.TryParse(version, out ver);
                            package.Version = ver;

                            if (
                                installedLanguages.Any(
                                    l =>
                                    LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant()) &&
                                    installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver))
                            {
                                continue;
                            }

                            if (packages.Any(p => p.Name == package.Name))
                            {
                                var existPackage = packages.First(p => p.Name == package.Name);
                                if (package.Version > existPackage.Version)
                                {
                                    packages.Remove(existPackage);
                                    packages.Add(package);
                                }
                            }
                            else
                            {
                                packages.Add(package);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //suppress for now - need to decide what to do when webservice is unreachable
                //throw;
                //same problem happens in InstallWizard.aspx.cs in BindLanguageList method
            }


            if (invalidPackages.Count > 0)
            {
                string pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />"));
                Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError);
            }

            grid.DataSource = packages;
            grid.DataBind();
        }
コード例 #31
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        private void ExerciseZip(CompressionMethod method, int compressionLevel,
                                 int size, string password, bool canSeek)
        {
            byte[] originalData = null;
            var compressedData = MakeInMemoryZip(ref originalData, method, compressionLevel, size, password, canSeek);

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            using (var inStream = new ZipInputStream(ms))
            {
                var decompressedData = new byte[size];
                if (password != null)
                {
                    inStream.Password = password;
                }

                var entry2 = inStream.GetNextEntry();

                if ((entry2.Flags & 8) == 0)
                {
                    Assert.AreEqual(size, entry2.Size, "Entry size invalid");
                }

                var currentIndex = 0;

                if (size > 0)
                {
                    var count = decompressedData.Length;

                    while (true)
                    {
                        var numRead = inStream.Read(decompressedData, currentIndex, count);
                        if (numRead <= 0)
                        {
                            break;
                        }
                        currentIndex += numRead;
                        count -= numRead;
                    }
                }

                Assert.AreEqual(currentIndex, size, "Original and decompressed data different sizes");

                if (originalData != null)
                {
                    for (var i = 0; i < originalData.Length; ++i)
                    {
                        Assert.AreEqual(decompressedData[i], originalData[i],
                                        "Decompressed data doesnt match original, compression level: " +
                                        compressionLevel);
                    }
                }
            }
        }
コード例 #32
0
ファイル: Form1.cs プロジェクト: lequant31/KhieunaitocaoFinal
        void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                lblStatus.Text           = "Đang cài đặt..";
                progress.Position        = 0;
                progress.Properties.Step = 1;

                ZipInputStream zipIn = new ZipInputStream(new MemoryStream(e.Result));
                ZipEntry       entry;

                int fileCount = 0;
                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    fileCount++;
                }
                progress.Properties.Maximum = fileCount;

                zipIn = new ZipInputStream(new MemoryStream(e.Result));
                while ((entry = zipIn.GetNextEntry()) != null)
                {
                    progress.PerformStep();
                    this.Update();

                    string path = Application.StartupPath + "\\" + (entry.Name.ToLower() != "updater.exe" ? entry.Name : "updaternew.exe");

                    if (entry.IsDirectory)
                    {
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        continue;
                    }

                    //File.Delete(AppDir + entry.Name);
                    FileStream streamWriter = File.Create(path);
                    long       size         = entry.Size;
                    byte[]     data         = new byte[size];
                    while (true)
                    {
                        size = zipIn.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, (int)size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();

                    if (entry.Name.ToLower() == "updater.exe")
                    {
                        RepairUpdater();
                    }
                }

                //Luu ver
                string       pathVersion = Application.StartupPath + "\\Version.txt";
                StreamWriter sw          = new StreamWriter(pathVersion);
                sw.WriteLine(NewVersion);
                sw.Close();
                //
                lblStatus.Text    = "Cài đặt hoàn tất";
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                MessageBox.Show("Đã xảy ra lỗi trong quá trình tải xuống", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #33
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void ExerciseGetNextEntry()
        {
            var compressedData = MakeInMemoryZip(
                true,
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
                new RuntimeInfo(null, true),
                new RuntimeInfo(CompressionMethod.Stored, 2, 50, null, true),
                new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true)
                );

            var ms = new MemoryStream(compressedData);
            ms.Seek(0, SeekOrigin.Begin);

            using (var inStream = new ZipInputStream(ms))
            {
                var buffer = new byte[10];

                ZipEntry entry;
                while ((entry = inStream.GetNextEntry()) != null)
                {
                    // Read a portion of the data, so GetNextEntry has some work to do.
                    inStream.Read(buffer, 0, 10);
                }
            }
        }
コード例 #34
0
ファイル: ModCompress.cs プロジェクト: SES-xuelan/XLAF
        /// <summary>
        /// Decompress
        /// </summary>
        /// <param name="inputStream">Zip inputStream</param>
        /// <param name="outputPath">output folder</param>
        /// <param name="password">password</param>
        /// <param name="unzipCallback">UnzipCallback</param>
        /// <returns></returns>
        public static bool Decompress(Stream inputStream, string outputPath, string password = null, UnzipCallback unzipCallback = null)
        {
            if ((null == inputStream) || string.IsNullOrEmpty(outputPath))
            {
                if (null != unzipCallback)
                {
                    unzipCallback.OnFinished(false);
                }

                return(false);
            }

            // create folder
            if (!Directory.Exists(outputPath))
            {
                Directory.CreateDirectory(outputPath);
            }

            // unzip
            ZipEntry entry = null;

            using (ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
                if (!string.IsNullOrEmpty(password))
                {
                    zipInputStream.Password = password;
                }

                while (null != (entry = zipInputStream.GetNextEntry()))
                {
                    if (string.IsNullOrEmpty(entry.Name))
                    {
                        continue;
                    }

                    if ((null != unzipCallback) && !unzipCallback.OnPreUnzip(entry))
                    {
                        continue;                           // filter
                    }
                    string filePathName = Path.Combine(outputPath, entry.Name);

                    // create folder
                    if (entry.IsDirectory)
                    {
                        Directory.CreateDirectory(filePathName);
                        continue;
                    }

                    // write to file
                    try {
                        using (FileStream fileStream = File.Create(filePathName)) {
                            byte[] bytes = new byte[1024];
                            while (true)
                            {
                                int count = zipInputStream.Read(bytes, 0, bytes.Length);
                                if (count > 0)
                                {
                                    fileStream.Write(bytes, 0, count);
                                }
                                else
                                {
                                    if (null != unzipCallback)
                                    {
                                        unzipCallback.OnPostUnzip(entry);
                                    }

                                    break;
                                }
                            }
                        }
                    } catch (System.Exception e) {
                        Debug.LogError(e.ToString());

                        if (null != unzipCallback)
                        {
                            unzipCallback.OnFinished(false);
                        }

                        return(false);
                    }
                }
            }

            if (null != unzipCallback)
            {
                unzipCallback.OnFinished(true);
            }

            return(true);
        }
コード例 #35
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void MixedEncryptedAndPlain()
        {
            var compressedData = MakeInMemoryZip(true,
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", false),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, false),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true)
                );

            var ms = new MemoryStream(compressedData);
            using (var inStream = new ZipInputStream(ms))
            {
                inStream.Password = "******";

                var extractCount = 0;
                var extractIndex = 0;
                ZipEntry entry;
                var decompressedData = new byte[100];

                while ((entry = inStream.GetNextEntry()) != null)
                {
                    extractCount = decompressedData.Length;
                    extractIndex = 0;
                    while (true)
                    {
                        var numRead = inStream.Read(decompressedData, extractIndex, extractCount);
                        if (numRead <= 0)
                        {
                            break;
                        }
                        extractIndex += numRead;
                        extractCount -= numRead;
                    }
                }
                inStream.Close();
            }
        }
コード例 #36
0
    public static string unZipFile(string TargetFile, string fileDir)
    {
        string rootFile = " ";

        try
        {
            //读取压缩文件(zip文件),准备解压缩
            inputStream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
            ZipEntry theEntry;
            string   path = fileDir;
            //解压出来的文件保存的路径

            string rootDir = " ";
            //根目录下的第一个子文件夹的名称
            while ((theEntry = inputStream.GetNextEntry()) != null)
            {
                rootDir = Path.GetDirectoryName(theEntry.Name);
                //得到根目录下的第一级子文件夹的名称
                if (rootDir.IndexOf("\\") >= 0)
                {
                    rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                }
                string dir = Path.GetDirectoryName(theEntry.Name);
                //根目录下的第一级子文件夹的下的文件夹的名称
                string fileName = Path.GetFileName(theEntry.Name);
                //根目录下的文件名称
                if (dir != " ")
                //创建根目录下的子文件夹,不限制级别
                {
                    if (!Directory.Exists(fileDir + "\\" + dir))
                    {
                        path = fileDir + "\\" + dir;
                        //在指定的路径创建文件夹
                        Directory.CreateDirectory(path);
                    }
                }
                else if (dir == " " && fileName != "")
                //根目录下的文件
                {
                    path     = fileDir;
                    rootFile = fileName;
                }
                else if (dir != " " && fileName != "")
                //根目录下的第一级子文件夹下的文件
                {
                    if (dir.IndexOf("\\") > 0)
                    //指定文件保存的路径
                    {
                        path = fileDir + "\\" + dir;
                    }
                }

                if (dir == rootDir)
                //判断是不是需要保存在根目录下的文件
                {
                    path = fileDir + "\\" + rootDir;
                }

                //以下为解压缩zip文件的基本步骤
                //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(path + "\\" + fileName);

                    int    size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = inputStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }

                    streamWriter.Close();
                }
            }

            inputStream.Close();

            return(rootFile);
        }
        catch (Exception ex)
        {
            // inputStream = null;
            return("1; " + ex.Message);
        }
    }
コード例 #37
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void SkipEncryptedEntriesWithoutSettingPassword()
        {
            var compressedData = MakeInMemoryZip(true,
                                                 new RuntimeInfo("1234", true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
                                                 new RuntimeInfo(null, true),
                                                 new RuntimeInfo(CompressionMethod.Stored, 2, 1, "4321", true),
                                                 new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true)
                );

            var ms = new MemoryStream(compressedData);
            var inStream = new ZipInputStream(ms);

            ZipEntry entry;
            while ((entry = inStream.GetNextEntry()) != null)
            {
            }

            inStream.Close();
        }
コード例 #38
0
        private async void Main_Load(object sender, System.EventArgs e)
        {
            var uiContext = SynchronizationContext.Current;

            uiContext.Post(UpdateCurrentOperation, "Searching for RemotePlay.exe...");
            _remotePlayPath = FindRemotePlay();
            if (string.IsNullOrEmpty(_remotePlayPath))
            {
                if (MessageBox.Show("The PS4 Remote Play couldn't be found. Please select the file that needs to be patched.",
                                    "Not found",
                                    MessageBoxButtons.OKCancel,
                                    MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                {
                    Environment.Exit(0);
                }

                using (var dialog = new OpenFileDialog())
                {
                    dialog.Title  = "Select the RemotePlay.exe you want to patch";
                    dialog.Filter = "RemotePlay.exe|RemotePlay.exe";

                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        Environment.Exit(0);
                    }

                    _remotePlayPath = dialog.FileName;
                }
            }

            // For some reason the FileVersion FileVersionInfo provides isn't exactly the one we're looking for.
            // Sometimes padding is added to one of the parts.
            var version     = FileVersionInfo.GetVersionInfo(_remotePlayPath);
            var fileVersion = $"{version.FileMajorPart}.{version.FileMinorPart}.{version.FileBuildPart}.{version.FilePrivatePart}";

            await Task.Run(() =>
            {
                try
                {
                    new RetryPolicy()
                    .MaxAttempts(int.MaxValue)
                    .Abort.IfException <Exception>(ex => MessageBox.Show($"An error occured while downloading the latest patches.\n{ex}", "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                    .Try(() =>
                    {
                        using (var cryptoProvider = new MD5CryptoServiceProvider())
                            using (var client = new WebClient())
                            {
                                uiContext.Post(UpdateCurrentOperation, "Computing RemotePlay.exe's hash...");
                                var hash = string.Join(string.Empty, cryptoProvider.ComputeHash(File.ReadAllBytes(_remotePlayPath)).Select(b => b.ToString("X2")));

                                uiContext.Post(UpdateCurrentOperation, "Downloading latest patches from GitHub...");
                                using (var zipStream = new ZipInputStream(client.OpenRead(PatchesLocation)))
                                {
                                    var zipEntry = zipStream.GetNextEntry();
                                    while (zipEntry != null)
                                    {
                                        var patchName = zipEntry.Name;

                                        if (patchName.StartsWith(fileVersion, StringComparison.InvariantCultureIgnoreCase) &&
                                            patchName.EndsWith(hash, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            using (var memoryStream = new MemoryStream())
                                            {
                                                zipStream.CopyTo(memoryStream);
                                                _patch = memoryStream.ToArray();
                                            }

                                            uiContext.Post(UpdateCurrentOperation, "Ready !");
                                            uiContext.Post(EnablePatchButton, true);
                                            return;
                                        }

                                        zipEntry = zipStream.GetNextEntry();
                                    }

                                    throw new Exception("Patch not found or RemotePlay.exe is already patched !");
                                }
                            }
                    });
                }
                catch (AggregateException)
                {
                    Environment.Exit(0);
                }
            });
        }
コード例 #39
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void CreateAndReadEmptyZip()
        {
            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);
            ZipEntry entry;
            while ((entry = inStream.GetNextEntry()) != null)
            {
                Assert.Fail("No entries should be found in empty zip");
            }
        }
コード例 #40
0
    /// <summary>
    /// 解压缩
    /// </summary>
    /// <param name="sourceFile">源文件</param>
    /// <param name="targetPath">目标路经</param>
    public static bool Decompress(string sourceFile, string targetPath, unzipProgressDelegate deleg)
    {
        errorMsg = "";
        long zipFileCount = 0;

        using (ZipFile zip = new ZipFile(sourceFile))
        {
            zipFileCount = zip.Count;
            zip.Close();
        }
        if (!File.Exists(sourceFile))
        {
            throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
        }
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(sourceFile)))
        {
            int      unZipCount = 0;
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                try
                {
                    string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
                    string fileName     = directorName + "/" + Path.GetFileName(theEntry.Name);
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    // 创建目录
                    if (Directory.Exists(directorName) == false && directorName.Length > 0)
                    {
                        Directory.CreateDirectory(directorName);
                    }
                    if (fileName != string.Empty)
                    {
                        using (FileStream streamWriter = File.Create(fileName))
                        {
                            int    size = 4096;
                            byte[] data = new byte[4 * 1024];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                                //deleg((float)((double)s.Position / s.Length));
                            }
                            streamWriter.Close();
                            unZipCount++;
                        }
                    }
                    if (deleg != null)
                    {
                        deleg((float)((float)unZipCount / (float)zipFileCount));
                    }
                }
                catch (Exception ex)
                {
                    errorMsg = ex.Message;
                    return(false);
                }
            }
        }
        return(true);
    }
コード例 #41
0
ファイル: ZipTests.cs プロジェクト: modulexcite/graveyard
        public void ParameterHandling()
        {
            var buffer = new byte[10];
            var emptyBuffer = new byte[0];

            var ms = new MemoryStream();
            var outStream = new ZipOutputStream(ms);
            outStream.IsStreamOwner = false;
            outStream.PutNextEntry(new ZipEntry("Floyd"));
            outStream.Write(buffer, 0, 10);
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            var inStream = new ZipInputStream(ms);
            var e = inStream.GetNextEntry();

            MustFailRead(inStream, null, 0, 0);
            MustFailRead(inStream, buffer, -1, 1);
            MustFailRead(inStream, buffer, 0, 11);
            MustFailRead(inStream, buffer, 7, 5);
            MustFailRead(inStream, buffer, 0, -1);

            MustFailRead(inStream, emptyBuffer, 0, 1);

            var bytesRead = inStream.Read(buffer, 10, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");

            bytesRead = inStream.Read(emptyBuffer, 0, 0);
            Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes");
        }
コード例 #42
0
        private string Descomprimir(string directorio, string zipFic = "")
        {
            string RutaArchivo = string.Empty;

            try
            {
                if (!zipFic.ToLower().EndsWith(".zip"))
                {
                    zipFic = Directory.GetFiles(zipFic, "*.zip")[0];
                }
                if (directorio == "")
                {
                    directorio = ".";
                }
                ZipInputStream z = new ZipInputStream(File.OpenRead(directorio + @"\" + zipFic));
                ZipEntry       theEntry;
                do
                {
                    theEntry = z.GetNextEntry();
                    if (theEntry != null)
                    {
                        string fileName = directorio + @"\" + Path.GetFileName(theEntry.Name);
                        if (!Directory.Exists(fileName))
                        {
                            if (Path.GetExtension(fileName).ToString().ToUpper() == ".XML")
                            {
                                RutaArchivo = fileName;
                                FileStream streamWriter;
                                try
                                {
                                    streamWriter = File.Create(fileName);
                                }
                                catch (DirectoryNotFoundException ex)
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                                    streamWriter = File.Create(fileName);
                                }
                                //
                                int    size;
                                byte[] data = new byte[2049];
                                do
                                {
                                    size = z.Read(data, 0, data.Length);
                                    if ((size > 0))
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }while (true);
                                streamWriter.Close();
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }while (true);
                z.Close();
                return(RutaArchivo);
            }
            catch (Exception ex)
            {
                //Log.Error(ex.Message, excepcion: ex);
            }
            return("");
        }
コード例 #43
0
		private static void  dumpZip(System.IO.StreamWriter out_Renamed, System.Uri url, System.String outfile)
		{
			System.IO.Stream in_Renamed = new System.IO.BufferedStream(System.Net.WebRequest.Create(url).GetResponse().GetResponseStream());
			try
			{
				//UPGRADE_ISSUE: Class 'java.util.zip.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				//UPGRADE_ISSUE: Constructor 'java.util.zip.ZipInputStream.ZipInputStream' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				ZipInputStream zipIn = new ZipInputStream(in_Renamed);
				//UPGRADE_ISSUE: Class 'java.util.zip.ZipEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipEntry'"
				//UPGRADE_ISSUE: Method 'java.util.zip.ZipInputStream.getNextEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
				ZipEntry zipEntry = zipIn.getNextEntry();
				while ((zipEntry != null))
				{
					//UPGRADE_TODO: Class 'java.net.URL' was converted to a 'System.Uri' which does not throw an exception if a URL specifies an unknown protocol. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1132'"
					//UPGRADE_ISSUE: Method 'java.util.zip.ZipEntry.getName' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipEntry'"
					System.Uri fileUrl = new System.Uri("jar:" + url.ToString() + "!/" + zipEntry.getName());
					if (isSwf(fileUrl))
						dumpSwf(out_Renamed, fileUrl, outfile);
					//UPGRADE_ISSUE: Method 'java.util.zip.ZipInputStream.getNextEntry' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javautilzipZipInputStream'"
					zipEntry = zipIn.getNextEntry();
				}
			}
			finally
			{
				in_Renamed.Close();
			}
		}
コード例 #44
0
 /// <summary>
 /// 解压缩目录
 /// </summary>
 /// <param name="zipDirectoryPath">压缩目录路径</param>
 /// <param name="unZipDirecotyPath">解压缩目录路径</param>
 /// <param name="password">密码</param>
 public static void DeCompress(string zipDirectoryPath, string unZipDirecotyPath, string password)
 {
     Log.Info("DeCompress-Begin");
     try
     {
         while (unZipDirecotyPath.LastIndexOf("\\", StringComparison.CurrentCultureIgnoreCase) + 1 ==
                unZipDirecotyPath.Length)                                                      //检查路径是否以"\"结尾
         {
             unZipDirecotyPath = unZipDirecotyPath.Substring(0, unZipDirecotyPath.Length - 1); //如果是则去掉末尾的"\"
             //Log.Debug("DeCompress-01");
         }
         //Log.Debug("DeCompress-02");
         using (var inputStream = new FileStream(zipDirectoryPath, FileMode.Open, FileAccess.Read))
         {
             using (var zipStream = new ZipInputStream(inputStream))
             {
                 //判断Password
                 if (!string.IsNullOrEmpty(password))
                 {
                     zipStream.Password = password;
                 }
                 ZipEntry zipEntry = null;
                 while ((zipEntry = zipStream.GetNextEntry()) != null)
                 {
                     string directoryName = Path.GetDirectoryName(zipEntry.Name);
                     string fileName      = Path.GetFileName(zipEntry.Name);
                     if (!string.IsNullOrEmpty(directoryName))
                     {
                         string directoryPath = Path.Combine(unZipDirecotyPath, directoryName);
                         if (!Directory.Exists(directoryPath))
                         {
                             Directory.CreateDirectory(directoryPath);
                         }
                     }
                     if (!string.IsNullOrEmpty(fileName))
                     {
                         //if (zipEntry.CompressedSize == 0)
                         //    break;
                         if (zipEntry.IsDirectory)//如果压缩格式为文件夹方式压缩
                         {
                             directoryName = Path.GetDirectoryName(unZipDirecotyPath + @"\" + zipEntry.Name);
                             if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
                             {
                                 Directory.CreateDirectory(directoryName);
                             }
                         }
                         else//2012-5-28修改,支持单个文件压缩时自己创建目标文件夹
                         {
                             if (!Directory.Exists(unZipDirecotyPath))
                             {
                                 Directory.CreateDirectory(unZipDirecotyPath);
                             }
                         }
                         //Log.Debug("test-def");
                         var singleFileName = unZipDirecotyPath + @"\" + zipEntry.Name;
                         FileUtil.DeleteFile(singleFileName);
                         using (var stream = new FileStream(unZipDirecotyPath + @"\" + zipEntry.Name,
                                                            FileMode.OpenOrCreate, FileAccess.Write))
                         //File.Create(unZipDirecotyPath + @"\" + zipEntry.Name))
                         {
                             while (true)
                             {
                                 var buffer = new byte[8192];
                                 int size   = zipStream.Read(buffer, 0, buffer.Length);
                                 if (size > 0)
                                 {
                                     stream.Write(buffer, 0, size);
                                 }
                                 else
                                 {
                                     break;
                                 }
                             }
                             //Log.Debug("test-hjk");
                             stream.Close();
                         }
                     }
                 }
                 zipStream.Close();
             }
             inputStream.Close();
         }
     }
     catch (IOException e)
     {
         Log.Error(e);
         throw new ApplicationException(e.Message, e);
     }
     catch (Exception e)
     {
         Log.Error(e);
         throw new ApplicationException(e.Message, e);
     }
 }
コード例 #45
0
    /// <summary>
    /// 功能:解压zip格式的文件。
    /// </summary>
    /// <param name="zipFilePath">压缩文件路径</param>
    /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
    /// <param name="err">出错信息</param>
    /// <returns>解压是否成功</returns>
    public static void UnZip(string zipFilePath, string unZipDir)
    {
        if (zipFilePath == string.Empty)
        {
            throw new Exception("压缩文件不能为空!");
        }
        if (!File.Exists(zipFilePath))
        {
            throw new System.IO.FileNotFoundException("压缩文件不存在!");
        }
        //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
        if (unZipDir == string.Empty)
        {
            unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
        }
        if (!unZipDir.EndsWith("/"))
        {
            unZipDir += "/";
        }
        if (!Directory.Exists(unZipDir))
        {
            Directory.CreateDirectory(unZipDir);
        }

        using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
        {
            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName      = Path.GetFileName(theEntry.Name);
                if (directoryName.Length > 0)
                {
                    Directory.CreateDirectory(unZipDir + directoryName);
                }
                if (!directoryName.EndsWith("/"))
                {
                    directoryName += "/";
                }
                if (fileName != String.Empty)
                {
                    using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                    {
                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
コード例 #46
0
        /// <summary>
        /// 解压ZIP格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,缺省值压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <param name="msg">返回消息</param>
        /// <returns>解压是否成功</returns>
        public bool UnZipFile(string zipFilePath, string unZipDir, out string msg)
        {
            msg = "";

            //判读路径是否为空
            if (zipFilePath == string.Empty || zipFilePath == null)
            {
                msg = "ZipFile No Selected";
                return(false);
            }

            //判读文件是否存在
            if (!File.Exists(zipFilePath))
            {
                msg = "ZipFile No Exists";
                return(false);
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
            if (unZipDir == string.Empty || unZipDir == null)
            {
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            }

            if (!unZipDir.EndsWith("//"))
            {
                unZipDir += "//";
            }

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

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName      = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("//"))
                        {
                            directoryName += "//";
                        }
                        if (fileName != String.Empty && fileName != null)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                            {
                                CopyStream(s, streamWriter);
                            }
                        }
                    } //end while
                }     //end using
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }

            msg = "UnZip Success ! ";
            return(true);
        }//end function
コード例 #47
0
        /// <summary>
        /// Extracts the next file from ZIP archive specified in <paramref name="fileStream" /> and save to the directory
        /// specified in <paramref name="destPath" />. The name may be changed slightly to ensure uniqueness in the directory.
        /// The full path to the extracted file is returned. If no file is found in the ZIP archive, an emptry string is returned.
        /// </summary>
        /// <param name="fileStream">A stream representing a ZIP file containing directories and files to be extracted
        /// to the Gallery Server Pro library.</param>
        /// <param name="destPath">The full path to the directory where the extracted file is to be saved.</param>
        /// <returns>Returns the full path to the extracted file.</returns>
        public string ExtractNextFileFromZip(Stream fileStream, string destPath)
        {
            this._zipStream = new ZipInputStream(fileStream);

            ZipEntry zipContentFile;
            if ((zipContentFile = this._zipStream.GetNextEntry()) != null)
            {
                string uniqueFilename = HelperFunctions.ValidateFileName(destPath, zipContentFile.Name);
                string uniqueFilepath = Path.Combine(destPath, uniqueFilename);

                ExtractFileFromZipStream(uniqueFilepath);

                return uniqueFilepath;
            }

            return String.Empty;
        }
コード例 #48
0
        }//end function

        /// <summary>
        /// 解压指定ZIP文件到当前路径
        /// </summary>
        /// <param name="zipFilePath">ZIP文件绝对路径</param>
        /// <param name="msg">返回消息</param>
        /// <returns>解压是否成功</returns>
        public bool UnZipFileToCurrentPath(string zipFilePath, out string msg)
        {
            msg = "";

            //判读路径是否为空
            if (zipFilePath == string.Empty || zipFilePath == null)
            {
                msg = "ZipFile No Selected";
                return(false);
            }

            //判读文件是否存在
            if (!File.Exists(zipFilePath))
            {
                msg = "ZipFile No Exists";
                return(false);
            }
            //解压到当前目录
            string unZipDir = zipFilePath.Substring(0, zipFilePath.LastIndexOf(@"\"));

            if (!unZipDir.EndsWith("//"))
            {
                unZipDir += "//";
            }

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

            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName      = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("//"))
                        {
                            directoryName += "//";
                        }
                        if (fileName != String.Empty && fileName != null)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
                            {
                                CopyStream(s, streamWriter);
                            }
                        }
                    } //end while
                }     //end using
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return(false);
            }

            msg = "UnZip Success ! ";
            return(true);
        }//end function
コード例 #49
0
        private static void ExtractFileToStream(ZipInputStream zipStream, Stream destStream)
        {
            int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize;
            byte[] data = new byte[bufferSize];

            int byteCount;
            while ((byteCount = zipStream.Read(data, 0, data.Length)) > 0)
            {
                destStream.Write(data, 0, byteCount);
            }
        }
コード例 #50
0
ファイル: NewCommand.cs プロジェクト: zazaqiming/abp
        public async Task ExecuteAsync(CommandLineArgs commandLineArgs)
        {
            var projectName = NamespaceHelper.NormalizeNamespace(commandLineArgs.Target);

            if (projectName == null)
            {
                throw new CliUsageException(
                          "Project name is missing!" +
                          Environment.NewLine + Environment.NewLine +
                          GetUsageInfo()
                          );
            }

            Logger.LogInformation("Creating your project...");
            Logger.LogInformation("Project name: " + projectName);

            var template = commandLineArgs.Options.GetOrNull(Options.Template.Short, Options.Template.Long);

            if (template != null)
            {
                Logger.LogInformation("Template: " + template);
            }

            var version = commandLineArgs.Options.GetOrNull(Options.Version.Short, Options.Version.Long);

            if (version != null)
            {
                Logger.LogInformation("Version: " + version);
            }

            var isTiered = commandLineArgs.Options.ContainsKey(Options.Tiered.Long);

            if (isTiered)
            {
                Logger.LogInformation("Tiered: yes");
            }

            var preview = commandLineArgs.Options.ContainsKey(Options.Preview.Long);

            if (preview)
            {
                Logger.LogInformation("Preview: yes if any exist for next version.");
            }

            var databaseProvider = GetDatabaseProvider(commandLineArgs);

            if (databaseProvider != DatabaseProvider.NotSpecified)
            {
                Logger.LogInformation("Database provider: " + databaseProvider);
            }

            var uiFramework = GetUiFramework(commandLineArgs);

            if (uiFramework != UiFramework.NotSpecified)
            {
                Logger.LogInformation("UI Framework: " + uiFramework);
            }

            var connectionString = GetConnectionString(commandLineArgs);

            if (connectionString != null)
            {
                Logger.LogInformation("Connection string: " + connectionString);
            }

            var mobileApp = GetMobilePreference(commandLineArgs);

            if (mobileApp != MobileApp.None)
            {
                Logger.LogInformation("Mobile App: " + mobileApp);
            }

            var gitHubAbpLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubAbpLocalRepositoryPath.Long);

            if (gitHubAbpLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Abp Local Repository Path: " + gitHubAbpLocalRepositoryPath);
            }

            var gitHubVoloLocalRepositoryPath = commandLineArgs.Options.GetOrNull(Options.GitHubVoloLocalRepositoryPath.Long);

            if (gitHubVoloLocalRepositoryPath != null)
            {
                Logger.LogInformation("GitHub Volo Local Repository Path: " + gitHubVoloLocalRepositoryPath);
            }

            var templateSource = commandLineArgs.Options.GetOrNull(Options.TemplateSource.Short, Options.TemplateSource.Long);

            if (templateSource != null)
            {
                Logger.LogInformation("Template Source: " + templateSource);
            }

            var createSolutionFolder = GetCreateSolutionFolderPreference(commandLineArgs);

            if (!createSolutionFolder)
            {
                Logger.LogInformation("Create Solution Folder: no");
            }

            var outputFolder = commandLineArgs.Options.GetOrNull(Options.OutputFolder.Short, Options.OutputFolder.Long);

            var outputFolderRoot =
                outputFolder != null?Path.GetFullPath(outputFolder) : Directory.GetCurrentDirectory();

            outputFolder = createSolutionFolder ?
                           Path.Combine(outputFolderRoot, SolutionName.Parse(projectName).FullName) :
                           outputFolderRoot;

            Volo.Abp.IO.DirectoryHelper.CreateIfNotExists(outputFolder);

            Logger.LogInformation("Output folder: " + outputFolder);

            commandLineArgs.Options.Add(CliConsts.Command, commandLineArgs.Command);

            var result = await TemplateProjectBuilder.BuildAsync(
                new ProjectBuildArgs(
                    SolutionName.Parse(projectName),
                    template,
                    version,
                    databaseProvider,
                    uiFramework,
                    mobileApp,
                    gitHubAbpLocalRepositoryPath,
                    gitHubVoloLocalRepositoryPath,
                    templateSource,
                    commandLineArgs.Options,
                    connectionString
                    )
                );

            using (var templateFileStream = new MemoryStream(result.ZipContent))
            {
                using (var zipInputStream = new ZipInputStream(templateFileStream))
                {
                    var zipEntry = zipInputStream.GetNextEntry();
                    while (zipEntry != null)
                    {
                        if (string.IsNullOrWhiteSpace(zipEntry.Name))
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var fullZipToPath = Path.Combine(outputFolder, zipEntry.Name);
                        var directoryName = Path.GetDirectoryName(fullZipToPath);

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

                        var fileName = Path.GetFileName(fullZipToPath);
                        if (fileName.Length == 0)
                        {
                            zipEntry = zipInputStream.GetNextEntry();
                            continue;
                        }

                        var buffer = new byte[4096]; // 4K is optimum
                        using (var streamWriter = File.Create(fullZipToPath))
                        {
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        zipEntry = zipInputStream.GetNextEntry();
                    }
                }
            }

            Logger.LogInformation($"'{projectName}' has been successfully created to '{outputFolder}'");
        }
コード例 #51
0
        public void LoadFile(string path)
        {
            InternalEntries = null;

            var jar = new FileInfo(path);
            this.FileName = jar;

            #region clazzLoader
            this.clazzLoader = default(InternalURLClassLoader);

            try
            {
                //var filePath = "jar:file://" + jar.FullName + "!/";

                // http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html
                // file:///C:/util/aws-android-sdk-0.2.0/lib/aws-android-sdk-0.2.0-ec2.jar

                // error @URLClassLoader: java.net.MalformedURLException: unknown protocol: c
                var url = new jvm::java.io.File(jar.FullName).toURL();

                // http://www.javakb.com/Uwe/Forum.aspx/java-programmer/34778/URLClassLoader-ClassNotFoundException
                // http://www.chinaup.org/docs/reference/java/net/URLClassLoader.html
                // http://www.docjar.com/html/api/sun/applet/AppletClassLoader.java.html


                // http://www.docjar.com/html/api/java/net/URLClassLoader.java.html
                // http://www.docjar.com/html/api/java/security/SecureClassLoader.java.html

                clazzLoader = new InternalURLClassLoader(new URL[] { url }, null);

            }
            catch (jvm::csharp.ThrowableException ex)
            {
                Console.WriteLine("error @URLClassLoader: " + ex);
                throw new InvalidOperationException();
            }
            #endregion


            //clazzLoader.CacheClassBytes(jar);

            #region Resolve
            clazzLoader.Resolve =
                name =>
                {
                    var f = default(FileInfo);

                    if (this.JavaArchiveResolve != null)
                    {
                        f = this.JavaArchiveResolve(name);
                        //clazzLoader.CacheClassBytes(f);
                    }

                    return f;
                };
            #endregion




            #region GetDynamicEnumerator
            this.GetDynamicEnumerator = () =>
            {

                var zip = default(ZipInputStream);

                try
                {
                    zip = new ZipInputStream(new jvm::java.io.FileInputStream(jar.FullName));
                }
                catch
                {
                    Console.WriteLine("error @ ZipInputStream");
                    throw new InvalidOperationException();
                }

                return (GetNextEntry)
                    delegate
                    {
                        if (zip == null)
                            return null;

                        var e = default(ZipEntry);

                        try
                        {
                            e = zip.getNextEntry();
                        }
                        catch
                        {
                        }

                        if (e == null)
                            return null;



                        var n = new Entry { Name = e.getName() };

                        if (clazzLoader != null)
                            if (n.Name.EndsWith(".class"))
                            {
                                var TypeFullName = n.Name.Substring(0, n.Name.Length - ".class".Length).Replace("/", ".");

                                var NestedTypeName = TypeFullName.SkipUntilLastOrEmpty("$");

                                var NestedTypeNameStartsWithNumber = NestedTypeName.StartsWithNumber();

                                if (NestedTypeNameStartsWithNumber)
                                {
                                    // we should skip nested types with only numbers
                                    // as we might not be able to load them

                                }
                                else
                                {

                                    n.TypeFullName = TypeFullName;


                                    Console.WriteLine("JavaArchiveReflector.Loadfile.InternalGetType almost set for " + n.TypeFullName);

                                    n.InternalGetType = delegate
                                    {
                                        Console.WriteLine("JavaArchiveReflector.Loadfile.InternalGetType - " + n.TypeFullName);

                                        var c = default(jvm::java.lang.Class);


                                        try
                                        {
                                            //Console.WriteLine(".deprecated loadClass: " + n.TypeFullName);

                                            c = clazzLoader.loadClass(n.TypeFullName);
                                        }
                                        catch (jvm::csharp.ThrowableException cc)
                                        {
                                            Console.WriteLine("** JavaArchiveReflector.Loadfile - error loadClass: " + n.TypeFullName + "; " + cc);

                                            //throw new InvalidOperationException();
                                        }

                                        // what if we need javax.jms.MessageListener ?
                                        if (c == null)
                                        {
                                            return null;
                                        }

                                        // cant be more explicit:P
                                        return jvm::ScriptCoreLibJava.Extensions.BCLImplementationExtensions.ToType(c);
                                    };
                                }
                            }

                        return n;
                    };
            };
            #endregion
        }
コード例 #52
0
ファイル: ErrorTests.cs プロジェクト: Belxjander/Asuna
        public void Error_UseZipEntryExtractWith_ZIS_wi10355()
        {
            string zipFileToCreate = "UseOpenReaderWith_ZIS.zip";
            CreateSmallZip(zipFileToCreate);

            // mixing ZipEntry.Extract and ZipInputStream is a no-no!!

            string extractDir = "extract";

            // Use ZipEntry.Extract with ZipInputStream.
            // This must fail.
            TestContext.WriteLine("Reading with ZipInputStream");
            using (var zip = new ZipInputStream(zipFileToCreate))
            {
                ZipEntry entry;
                while ((entry = zip.GetNextEntry()) != null)
                {
                    entry.Extract(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }
コード例 #53
0
ファイル: ZipUtility.cs プロジェクト: haimon74/KanNaim
		/// <summary>
		/// Releases unmanaged and - optionally - managed resources
		/// </summary>
		/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
		protected virtual void Dispose(bool disposing)
		{
			if (!this._hasBeenDisposed)
			{
				// Dispose of resources held by this instance.
				if (this._zipStream != null)
				{
					this._zipStream.Dispose();
					this._zipStream = null;
				}

				// Set the sentinel.
				this._hasBeenDisposed = true;
			}
		}
コード例 #54
0
        private void InstallUpdateFromZip(string zipFile, string outFolder, HashSet <string> filesNotUpdated)
        {
            using (FileStream fs = new FileStream(zipFile, FileMode.Open))
            {
                using (var zipInputStream = new ZipInputStream(fs))
                {
                    while (zipInputStream.GetNextEntry() is ZipEntry zipEntry)
                    {
                        var    entryFileName    = zipEntry.Name;
                        string relativeFilePath = entryFileName.Substring(0, entryFileName.Length - 4);



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

                        // Skip directory entry
                        if (Path.GetFileName(fullZipToPath).Length == 0)
                        {
                            continue;
                        }

                        if (entryFileName.EndsWith(".del"))
                        {
                            string fileToDelete = fullZipToPath.Substring(0, fullZipToPath.Length - 4);
                            File.Delete(fileToDelete);
                            filesNotUpdated.Remove(relativeFilePath);
                            continue;
                        }

                        if (entryFileName.EndsWith(".new"))
                        {
                            fullZipToPath = fullZipToPath.Substring(0, fullZipToPath.Length - 4);
                            filesNotUpdated.Remove(relativeFilePath);
                        }

                        // 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))
                        {
                            // 4K is optimum
                            var buffer = new byte[4096];
                            StreamUtils.Copy(zipInputStream, streamWriter, buffer);
                        }

                        if (entryFileName.EndsWith(".upd"))
                        {
                            string oldFile = fullZipToPath.Substring(0, fullZipToPath.Length - 4);
                            string newFile = oldFile + ".new";
                            try
                            {
                                DoDecode(newFile, oldFile, fullZipToPath);
                                filesNotUpdated.Remove(relativeFilePath);
                                File.Delete(fullZipToPath);
                                File.Delete(oldFile);
                                File.Move(newFile, oldFile);
                            }
                            catch {
                                File.Delete(fullZipToPath);
                                filesNotUpdated.Add(relativeFilePath);
                            }
                        }
                    }
                }
            }
        }
コード例 #55
0
ファイル: ClassZip.cs プロジェクト: ewin66/Jep
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">解压目标存放目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }
            ZipInputStream s        = null;
            ZipEntry       theEntry = null;
            string         fileName;
            FileStream     streamWriter = null;

            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        streamWriter = File.Create(fileName);
                        int    size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
コード例 #56
0
ファイル: TDownloaderUnity.cs プロジェクト: pcion123/TinyBee
        protected override IEnumerator IDownloadZip(string ip, string hostName, rRes data)
        {
            mLogger.Log("start download -> " + data.FileName);

            //設置下載路徑
            string path = GetLocation(ip, hostName) + data.Path + data.FileName;

            using (WWW bundle = new WWW(path))
            {
                yield return(bundle);

                //檢查下載錯誤訊息
                if (bundle.error != null)
                {
                    mStatus = eStatus.Error;
                    mOnError.InvokeGracefully(bundle.error);
                    mLogger.Log(bundle.error);
                    yield break;
                }

                //檢查是否下載完成
                if (bundle.isDone == true)
                {
                    //設置存檔路徑
                    string sPath = TinyContext.Instance.DataPath + data.Path;
                    string sName = data.FileName;
                    TFile.Save(sPath, sName, bundle.bytes);

                    using (FileStream fileStream = new FileStream(sPath + sName, FileMode.Open, FileAccess.Read))
                    {
                        using (ZipInputStream zipInputStream = new ZipInputStream(fileStream))
                        {
                            ZipEntry zipEntry;

                            // 逐一取出壓縮檔內的檔案(解壓縮)
                            while ((zipEntry = zipInputStream.GetNextEntry()) != null)
                            {
                                string zPath = TinyContext.Instance.DataPath + data.Path + zipEntry.Name;

                                //檢查是否存在舊檔案
                                if (File.Exists(zPath) == true)
                                {
                                    File.Delete(zPath);
                                }

                                mLogger.Log(zipEntry.Name);

                                using (FileStream fs = File.Create(zPath))
                                {
                                    while (true)
                                    {
                                        int size = zipInputStream.Read(mBuffer, 0, mBuffer.Length);

                                        if (size > 0)
                                        {
                                            fs.Write(mBuffer, 0, size);
                                        }
                                        else
                                        {
                                            break;
                                        }

                                        yield return(null);
                                    }
                                    fs.Close();
                                }
                                yield return(null);
                            }
                            zipInputStream.Close();
                        }
                        fileStream.Close();
                    }

#if !UNITY_TVOS || UNITY_EDITOR
                    File.Delete(sPath + sName);
#endif
                }
                else
                {
                    mStatus = eStatus.Error;
                    mOnError.InvokeGracefully(string.Format("下載失敗 -> {0}", bundle.url));
                    mLogger.Log(string.Format("下載失敗 -> {0}", bundle.url));
                }
            }
            mLogger.Log("end download -> " + data.FileName);
            Resources.UnloadUnusedAssets();
        }
コード例 #57
0
  public static string[] getDirectories( string zipFilename, string folderPath )
  {
    List<string> dirList = new List<string>();

    using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename)))
    {
      ZipEntry entry;
      while ((entry = inputStream.GetNextEntry()) != null)
      {
        if ( entry.FileName.StartsWith( folderPath )  )
        {
          char[] charsToTrim = { '/' };
          string entryName = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim );
          //Message.Log("entryName: '" + entryName + "'" );

          // extract first directory.
          int idx = entryName.IndexOf( "/" );
          if ( idx >= 0 )
          {
            string dirEntry = entryName.Substring( 0, idx );
            if ( !dirList.Contains( dirEntry ) )
              dirList.Add( entryName.Substring( 0, idx ) );
          }
        }
      }
    }

    return dirList.ToArray();
  }
コード例 #58
0
ファイル: ZipUtil.cs プロジェクト: ZqWong/UnityAssetsUpdate
        public IEnumerator SaveZip(
            string ZipID,
            byte[] ZipByte,
            Action <float> updateProgress,
            string password = null)
        {
            this.UpdateProgress = updateProgress;
            yield return((object)new WaitForSeconds(0.5f));

            if (!Directory.Exists(ZipID))
            {
                Directory.CreateDirectory(ZipID);
            }
            Encoding gbk = Encoding.GetEncoding("gbk");

            ZipConstants.DefaultCodePage = gbk.CodePage;
            Stream stream = (Stream) new MemoryStream(ZipByte);

            this.zipStream         = new ZipInputStream(stream);
            this.m_currentFileSize = this.GetZipBytes(ZipByte);
            if (!string.IsNullOrEmpty(password))
            {
                this.zipStream.Password = password;
            }
            while ((this.ent = this.zipStream.GetNextEntry()) != null)
            {
                this.ent.IsUnicodeText = true;
                if (!string.IsNullOrEmpty(this.ent.Name) && !this.ent.Name.EndsWith(".meta"))
                {
                    string   fileName = Path.Combine(ZipID, this.ent.Name);
                    FileInfo file     = new FileInfo(fileName);
                    if (file.Directory != null && !file.Directory.Exists)
                    {
                        file.Directory.Create();
                    }
                    fileName = fileName.Replace('\\', '/');
                    if (fileName.EndsWith("/"))
                    {
                        Directory.CreateDirectory(fileName);
                    }
                    else
                    {
                        this.fs = File.Create(fileName);
                        int size = this.deltaSize;
                        this.data = new byte[size];
                        yield return((object)this.ReadZip(this.zipStream, this.data, size, this.fs));

                        fileName = (string)null;
                        file     = (FileInfo)null;
                    }
                }
            }
            yield return((object)new WaitForEndOfFrame());

            if (this.UpdateProgress != null)
            {
                this.UpdateProgress(1f);
            }
            this.AllDispose();
            yield return((object)null);
        }
コード例 #59
0
ファイル: ErrorTests.cs プロジェクト: Belxjander/Asuna
        public void Error_UseOpenReaderWith_ZIS_wi10923()
        {
            string zipFileToCreate = "UseOpenReaderWith_ZIS.zip";
            CreateSmallZip(zipFileToCreate);

            // mixing OpenReader and ZipInputStream is a no-no!!
            int n;
            var buffer = new byte[2048];

            // Use OpenReader with ZipInputStream.
            // This must fail.
            TestContext.WriteLine("Reading with ZipInputStream");
            using (var zip = new ZipInputStream(zipFileToCreate))
            {
                ZipEntry entry;
                while ((entry = zip.GetNextEntry()) != null)
                {
                    TestContext.WriteLine("  Entry: {0}", entry.FileName);
                    using (Stream file = entry.OpenReader())
                    {
                        while((n= file.Read(buffer,0,buffer.Length)) > 0) ;
                    }
                    TestContext.WriteLine("  -- OpenReader() is done. ");
                }
            }
        }
コード例 #60
0
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="_depositPath">压缩文件路径</param>
        /// <param name="_floderPath">解压的路径</param>
        /// <returns></returns>
        public bool DeCompressionZip(string _depositPath, string _floderPath)
        {
            bool       result = true;
            FileStream fs     = null;

            try
            {
                ZipInputStream InpStream = new ZipInputStream(File.OpenRead(_depositPath));
                ZipEntry       ze        = InpStream.GetNextEntry(); //获取压缩文件中的每一个文件
                Directory.CreateDirectory(_floderPath);              //创建解压文件夹
                while (ze != null)                                   //如果解压完ze则是null
                {
                    if (ze.IsFile)                                   //压缩zipINputStream里面存的都是文件。带文件夹的文件名字是文件夹\\文件名
                    {
                        string[] strs = ze.Name.Split('\\');         //如果文件名中包含’\\‘则表明有文件夹
                        if (strs.Length > 1)
                        {
                            //两层循环用于一层一层创建文件夹
                            for (int i = 0; i < strs.Length - 1; i++)
                            {
                                string floderPath = _floderPath;
                                for (int j = 0; j < i; j++)
                                {
                                    floderPath = floderPath + "\\" + strs[j];
                                }
                                floderPath = floderPath + "\\" + strs[i];
                                Directory.CreateDirectory(floderPath);
                            }
                        }
                        fs = new FileStream(_floderPath + "\\" + ze.Name, FileMode.OpenOrCreate, FileAccess.Write);//创建文件
                        //循环读取文件到文件流中
                        while (true)
                        {
                            byte[] bts = new byte[1024];
                            int    i   = InpStream.Read(bts, 0, bts.Length);
                            if (i > 0)
                            {
                                fs.Write(bts, 0, i);
                            }
                            else
                            {
                                fs.Flush();
                                fs.Close();
                                break;
                            }
                        }
                    }
                    ze = InpStream.GetNextEntry();
                }
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                errorMsg = ex.Message;
                result   = false;
            }
            return(result);
        }