public override string Encrypt(string message) { switch (ProviderType) { case ProviderType.Simple: return(string.IsNullOrEmpty(message) ? string.Empty : Convert.ToBase64String(Encoding.UTF8.GetBytes(message))); case ProviderType.SimpleZip: if (string.IsNullOrEmpty(message)) { return(string.Empty); } var zipUtil = new ZipUtil(); return(Convert.ToBase64String(zipUtil.Compress(message))); } return(base.Encrypt(message)); }
static void UploadPackage() { string packagePath = MouseSelector.GetSelectedPathOrFallback(); string packageConfigPath = packagePath.EndsWith(".asset") ? packagePath : packagePath.Append(".asset").ToString(); if (File.Exists(packageConfigPath)) { string err = string.Empty; PackageConfig config = PackageConfig.LoadFromPath(packageConfigPath); string serverUploaderPath = Application.dataPath.CombinePath(config.PackageServerGitUrl.GetLastWord()); if (!Directory.Exists(serverUploaderPath)) { RunCommand(string.Empty, "git clone ".Append(config.PackageServerGitUrl).ToString()); } ZipUtil.ZipDirectory(config.PackagePath, IOUtils.CreateDirIfNotExists(serverUploaderPath.CombinePath(config.Name)).CombinePath(config.Name + ".zip")); PackageListConfig .MergeGitClonedPackageList(config) .SaveExport(config.PackageServerGitUrl); RunCommand(config.PackageServerGitUrl.GetLastWord(), string.Format( "git add . && git commit -m \"{0}\" && git push", config.ReleaseNote.IsNullOrEmpty() ? "no release note" : config.Name.Append(" ").Append(config.Version).AppendFormat(" {0}", config.ReleaseNote).ToString())); RunCommand(string.Empty, "rm -rf " + config.PackageServerGitUrl.GetLastWord()); AssetDatabase.Refresh(); Application.OpenURL(config.PackageServerGitUrl); } else { Log.W("no package.json file in folder:{0}", packagePath); } }
private int ReadZip(string filepath, string fileName) { int returnValue = 0; string extractedPath = string.Empty; string destPath = filepath + "\\extracted"; ZipUtil.UnZipFiles(filepath + "\\" + fileName, destPath, ref extractedPath, SageFrame.Common.RegisterModule.Common.Password, false); _provider.ExtractedPath = destPath; _provider.TempFolderPath = filepath; _provider.TempFileName = fileName; if (!string.IsNullOrEmpty(_provider.ExtractedPath) && Directory.Exists(_provider.ExtractedPath)) { switch (Step1CheckLogic(_provider.ExtractedPath, _provider)) { case 0: //No manifest file DeleteTempDirectory(_provider.TempFolderPath); returnValue = 3; break; case -1: //Invalid Manifest file DeleteTempDirectory(_provider.TempFolderPath); returnValue = 4; break; case 1: //Already exist returnValue = 2; break; case 2: //Fresh Installation returnValue = 1; break; } } else { returnValue = 0; } return(returnValue); }
public FetchResult <List <LogFile> > FetchLogFiles(string path) { // _parserSelector.SetTemplate(@"{date} <#> {thread} <#> {level:Level} <#> {logger} <#> {content} <#> {id} <#> {exception} <#>" + Environment.NewLine); var isTempPath = false; var tempFolder = string.Empty; string extractionPath; var extensionFilter = @".*\.log(\.[0-9]+)?"; if (File.Exists(path)) { // zip file var extension = Path.GetExtension(path); if (extension == ".zip") { var outFolder = PathUtil.GetTemporaryDirectory(); ZipUtil.ExtractZipFile(path, string.Empty, extensionFilter, outFolder); tempFolder = outFolder; extractionPath = outFolder; } else { return(new FetchResult <List <LogFile> >($"Format invalide : '{extension}'.")); } } else { extractionPath = path; } if (Directory.Exists(extractionPath)) { var files = new List <LogFile>(); foreach (var file in EnumerateFiles(extractionPath, extensionFilter)) { var logFile = new LogFile(file, _parserSelector, _moduleClassifier); files.Add(logFile); } _folderToDeleteOnExit.Add(tempFolder); return(files.ToFetchResult(tempFolder)); } return(new FetchResult <List <LogFile> >("Le chemin n'existe pas.")); }
public override string Decrypt(string encryptedMessage) { switch (ProviderType) { case ProviderType.Simple: return(string.IsNullOrEmpty(encryptedMessage) ? string.Empty : Encoding.UTF8.GetString(Convert.FromBase64String(encryptedMessage))); case ProviderType.SimpleZip: if (string.IsNullOrEmpty(encryptedMessage)) { return(string.Empty); } var src = Convert.FromBase64String(encryptedMessage); var zipUtil = new ZipUtil(); return(zipUtil.Decompress(src)); } return(base.Decrypt(encryptedMessage)); }
private void DeCompress(SoapMessage message) { if (!encryptMessage) { CopyBinaryStream(oldStream, newStream); newStream.Position = 0; } if (compressMessage) { newStream.Position = 0; Stream ms = new MemoryStream(); CopyBinaryStream(newStream, ms); ms.Position = 0; ms = ZipUtil.DeCompressStream(ms); ms.Position = 0; newStream.Position = 0; CopyBinaryStream(ms, newStream); newStream.Position = 0; } }
public override ResultadoOperacionDto EjecutarDistribucion(DocumentoInstanciaXbrlDto instancia, IDictionary <string, object> parametros) { var resultado = new ResultadoOperacionDto(); LogUtil.Info("Ejecutando Distribución JSON para documento: " + instancia.IdDocumentoInstancia + ", archivo: " + instancia.Titulo); try { string objJson = JsonConvert.SerializeObject(instancia, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); byte[] zipBytes = ZipUtil.GZip(objJson); //AgregarArchivoAListaJson(instancia); resultado.Resultado = true; ArchivoDocumentoInstancia archivo = new ArchivoDocumentoInstancia(); archivo.Archivo = zipBytes; archivo.IdDocumentoInstancia = (long)instancia.IdDocumentoInstancia; archivo.IdTipoArchivo = TipoArchivoConstants.ArchivoJson; ArchivoDocumentoInstanciaRepository.AgregaDistribucion(archivo); objJson = null; } catch (Exception ex) { var detalleError = new Dictionary <string, object>() { { "Error", "Error ejecutando Distribución JSON para documento: " + instancia.IdDocumentoInstancia + ", archivo: " + instancia.Titulo + ":" + ex.Message }, { "Excepsion", ex } }; LogUtil.Error(detalleError); resultado.Resultado = false; resultado.Mensaje = "Ocurrió un error al ejecutar la Distribución JSON para el archivo:" + instancia.IdDocumentoInstancia + ", archivo" + instancia.Titulo + ": " + ex.Message; resultado.Excepcion = ex.StackTrace; } return(resultado); }
IEnumerator DownloadDocRoutines(int doc_id) { string url = _urlZIP + doc_id + "&juego='sandwich'"; Debug.Log("DEntro"); WWW postName = new WWW(url); yield return(postName); //creamos el ZIP de las rutinas que ha creado el terapeuta se llama id_doc.zip ej. 13.zip //yield return new WaitForSeconds (5f); Debug.Log(postName.text.ToString() + "Hola"); if (postName.text.ToString().Contains("ZIPcreated")) //si existen rutinas creadas por el terapeuta descargamos el zip de esas rutinas { url = "http://132.248.16.11/unity/" + doc_id + ".zip"; //WWWForm form = new WWWForm(); WWW ww = new WWW(url); yield return(ww); //aqui ya descargamos el zip if (ww.error == null) { string fullPath = pathStoreAllInfo + "\\" + doc_id + ".zip"; //ruta donde guardamos el ZIP que descargamos File.WriteAllBytes(fullPath, ww.bytes); string exportLocation = pathStoreAllInfo + "\\"; //ruta donde extraemos el contenido del ZIP ej. "C:/Users/Yoás/Desktop//" ZipUtil.Unzip(fullPath, exportLocation); // using(ZipFile zip=ZipFile.Read(fullPath)){ // //extrayendo // foreach(ZipEntry z in zip){ // z.Extract(exportLocation,ExtractExistingFileAction.OverwriteSilently); // } // } //yield return new WaitForSeconds(2f); File.Delete(fullPath); //borramos el ZIP //borramos el ZIP del servidor url = _urlDeleteZIP + doc_id; WWW postName2 = new WWW(url); yield return(postName2); } } }
void Start() { // unzip string zipfilePath = "Assets/Resources/data/" + Sandbox + "/" + Version + ".tgz"; string exportLocation = "Assets/Resources/data/" + Sandbox; try { ZipUtil.Unzip(zipfilePath, exportLocation); } catch (Exception e) { Debug.Log(e.ToString()); } string path = "zip path: data/" + Sandbox + "/" + Version + "/manifest"; TextAsset txt = (TextAsset)Resources.Load("data/" + Sandbox + "/" + Version + "/manifest", typeof(TextAsset)); string content = txt.text; Dictionary <string, System.Object> manifest = MiniJSON.Json.Deserialize(JSON.Parse(content).ToString()) as Dictionary <string, System.Object>; Dictionary <string, System.Object> cards = manifest ["Cards"] as Dictionary <string, System.Object>; List <System.Object> cardsCards = cards ["Cards"] as List <System.Object>; List <string> cardsFiles = new List <string> (); foreach (string s in cardsCards) { cardsFiles.Add(s); } LoadCardData(cardsFiles); List <System.Object> decks = manifest ["Decks"] as List <System.Object>; List <string> decksFiles = new List <string> (); foreach (System.Object o in decks) { string deckName = (string)o; decksFiles.Add(deckName); } LoadDeckData(decksFiles); }
private bool zipFile(string zipfileprefix) { if (Directory.Exists(datapath)) { string[] filelists = Directory.GetFiles(datapath); if (filelists.Length <= 0) { return(true); } ZipUtil zipobj = new ZipUtil(); if (zipobj.ZipFile(zipfileprefix, zippath, datapath)) { logstr.Append("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ... 压缩文件成功。"); } else { logstr.Append("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] ... 压缩文件失败。"); } } FileUtil.deleteFile(datapath, "", ".xml", 0); return(true); }
public bool GenerateSpoolFromReport(ReportImage report) { try { using (var ctx = new ReportContext()) { //zipar a imagem var imageZipped = ZipUtil.ZipFromBytes(report.ReportImageData); //criaçao do relatorio var imgSave = new ReportSpool(DateTime.Now, report.ReportName, imageZipped); return(ctx.ReportSpoolDao.Save(imgSave)); } } catch (Exception ex) { Console.WriteLine("Falha na geração do spool"); LoggerUtilIts.GenerateLogs(ex, "Falha na geração do spool do relatório"); return(false); } }
static void BuildSelectionFolderBundle() { foreach (Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets)) { //if (!(obj is Texture2D)) continue; if (!(obj is UnityEngine.AudioClip) && !(obj is Texture2D) && !(obj is TextAsset) && !(obj is UnityEngine.RuntimeAnimatorController) && !(obj is UnityEngine.GameObject) && !(obj is UnityEngine.AnimationClip)) { continue; } string fullPath = AssetDatabase.GetAssetOrScenePath(obj); string fliterStr = "Resources"; int beginIndex = fullPath.IndexOf(fliterStr) + fliterStr.Length + 1; string objPath = fullPath.Substring(beginIndex, fullPath.LastIndexOf("/") - beginIndex); string dataPath = Application.dataPath; string outPath = dataPath + "/AssetBundles/" + objPath; if (!Directory.Exists(outPath)) { DirectoryInfo dirInfo = Directory.CreateDirectory(outPath); Debug.Log("Create a new direcory: " + dirInfo.FullName); } BuildAssetBundleOptions options = BuildAssetBundleOptions.DeterministicAssetBundle | BuildAssetBundleOptions.UncompressedAssetBundle | BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets; string fileName = outPath + "/" + obj.name + ".assetbundle"; BuildPipeline.PushAssetDependencies(); BuildPipeline.BuildAssetBundle(obj, null, fileName, options, AssetBundleTarget); BuildPipeline.PopAssetDependencies(); ZipUtil.CompressFileLZMA(fileName, outPath + "/" + obj.name + ".zip"); File.Delete(fileName); } }
public void LoadOsz() { string[] getPath = SFB.StandaloneFileBrowser.OpenFilePanel("開啟譜面", Application.dataPath, "osz", false); string path = getPath[0]; Debug.Log("讀取譜面開始=" + path); var readOsz = File.ReadAllBytes(path); string tempPath = Application.temporaryCachePath + "\\SongCache-" + System.DateTime.Now.ToString("yyyyMMdd-HHmmss"); Directory.CreateDirectory(tempPath); ZipUtil.Unzip(path, tempPath); Debug.Log("osz解壓完成=" + tempPath); string newFolderName = "ERROR"; foreach (var f in Directory.GetFiles(tempPath)) { if (Path.GetExtension(f) == ".osu") { OsuFile o = new OsuFile(f); newFolderName = o.Title + "-" + o.Artist; newFolderName = ToLegalPath(newFolderName); Debug.Log("新曲包名稱: " + newFolderName); break; } } if (Directory.Exists(Application.persistentDataPath + "\\Songs\\" + newFolderName)) { Debug.LogWarning("已經存在同一首歌"); } else { Debug.Log(tempPath + " | " + Application.persistentDataPath + "\\Songs\\" + newFolderName); Directory.Move(tempPath, Application.persistentDataPath + "\\Songs\\" + newFolderName); } SongPrinter.instance.Reprint(); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Response.Clear(); string path = RequestString("path"); if (path.IsNotEmpty()) { var directory = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/MaterialFiles")); path = Path.Combine(directory.FullName, path.TrimStart('\\')); if (Directory.Exists(path)) { var zipDir = new DirectoryInfo(path); string fileName = zipDir.Name + ".zip"; string targetPhysicalPath = HttpContext.Current.Server.MapPath("~/Temp"); targetPhysicalPath = Path.Combine(targetPhysicalPath, fileName); if (ZipUtil.CreateZip(path, targetPhysicalPath)) { WriteFile("~/Temp/" + fileName); } else { Response.Write("系统异常,请联系平台开发人员!"); } } else { Response.Write(string.Format("对不起,文件目录:{0} 不存在!", path)); } } else { Response.Write("参数错误"); } Response.End(); } }
static void PackAssets() { Debug.Log("begin pack"); Stopwatch sp = new Stopwatch(); sp.Start(); BuildSetting bs = GetBuildSettingAsset(); string path = Application.dataPath.Replace("Assets", "") + bs.buildPath; path = path.Replace('/', '\\'); string content = ""; float progress = 0f; try { ZipUtil.PackDirectory(path, Config.StreamingAssetsPath + "/data.zip", (cur, total) => { progress = (float)cur / total; content = (progress * 100).ToString("0.0") + "% " + (cur / 1024d / 1024d).ToString("0.0") + "M/" + (total / 1024d / 1024d).ToString("0.0") + "M"; EditorUtility.DisplayProgressBar("pack assets to zip", content, progress); }, () => { Debug.Log("pack finish! 耗时:" + sp.Elapsed.TotalSeconds + "s"); }); } catch (Exception e) { throw new Exception(e.Message); } finally { EditorUtility.ClearProgressBar(); AssetDatabase.Refresh(); } }
public void extractFile(string file) { extracted = false; #if !(UNITY_WEBPLAYER || UNITY_WEBGL) string[] dir = file.Split(System.IO.Path.DirectorySeparatorChar); string filename = dir[dir.Length - 1].Split('.')[0]; string exportLocation = getCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + "Games" + System.IO.Path.DirectorySeparatorChar + filename; ZipUtil.Unzip(file, exportLocation); foreach (string f in System.IO.Directory.GetFiles(exportLocation)) { if (!f.Contains(".xml")) { System.IO.File.Delete(f); } } string[] tmp; foreach (string f in System.IO.Directory.GetDirectories(exportLocation)) { tmp = f.Split(System.IO.Path.DirectorySeparatorChar); if (tmp[tmp.Length - 1] != "assets" && tmp[tmp.Length - 1] != "gui") { System.IO.Directory.Delete(f, true); } } VideoConverter converter = new VideoConverter(); foreach (string video in System.IO.Directory.GetFiles(exportLocation + "/assets/video/")) { converter.Convert(video); } extracted = true; #endif }
private string UnzipFile(string zipfilePath, string identificardor) { string exportLocation = ""; if (zipfilePath != "") { string nombrefichero = ""; string[] auxarray = zipfilePath.Split('/'); string aux = auxarray[auxarray.Length - 1]; print(aux); nombrefichero = aux.Remove(aux.Length - 4, 4); print("--" + nombrefichero); exportLocation = rutaBaseDescargas + nombrefichero + "-" + identificardor + "/"; ZipUtil.Unzip(zipfilePath, exportLocation); textoLog.text += exportLocation + "\n"; } return(exportLocation + "files/"); }
public override void FinishDownLoad(WWW tmpWWW) { string zipPath = Application.temporaryCachePath + "/tempZip.zip"; if (OutPutPath == null) { OutPutPath = IPathTools.GetAssetPersistentPath() + "/"; //数据目录 } var data = tmpWWW.bytes; File.WriteAllBytes(zipPath, data); try { ZipUtil.Unzip(zipPath, outPutPath); } catch (System.Exception e) { Debuger.Log(" e ===" + e); } }
public UEPubReader(string file) { bookItems = new Dictionary <string, string> (); spine = new List <string> (); var fileArray = file.Split('.'); if (fileArray [fileArray.Length - 1].ToLower() != "epub") { Debug.LogErrorFormat("The file {0} is not a .epub file", file); return; } fileArray = string.Join(".", fileArray, 0, fileArray.Length - 1).Split(System.IO.Path.DirectorySeparatorChar); var folderName = fileArray[fileArray.Length - 1]; epubFolderLocation = Application.temporaryCachePath + "/" + folderName; ZipUtil.Unzip(file, epubFolderLocation); ParseContainer(); ParseOPF(); }
public void TestReProcesarDistribucionPDF() { LogUtil.LogDirPath = @"..\..\TestOutput\"; LogUtil.Inicializa(); var xpe = XPEServiceImpl.GetInstance(true); var listaParametros = ObtenParametrosTest(); var procesador = (IProcesarDistribucionDocumentoXBRLService)applicationContext.GetObject("ProcesarDistribucionDocumentoXBRLService"); var servicioAlmacenamiento = (IAlmacenarDocumentoInstanciaService)applicationContext.GetObject("AlmacenarDocumentoInstanciaService"); var DocumentoInstanciaRepository = (IDocumentoInstanciaRepository)applicationContext.GetObject("DocumentoInstanciaRepository"); var VersionDocumentoInstanciaRepository = (IVersionDocumentoInstanciaRepository)applicationContext.GetObject("VersionDocumentoInstanciaRepository"); var DistribucionExportarPDFLocal = (DistribucionExportarPdfXBRL)applicationContext.GetObject("DistribucionExportarPDFLocal"); var ArchivoDocumentoInstanciaRepository = (IArchivoDocumentoInstanciaRepository)applicationContext.GetObject("ArchivoDocumentoInstanciaRepository"); var xpeServ = XPEServiceImpl.GetInstance(true); var idDocumentoInstancia = 10317; var instanciaDb = DocumentoInstanciaRepository.GetById(idDocumentoInstancia); var versionBD = VersionDocumentoInstanciaRepository .ObtenerUltimaVersionDocumentoInstancia(idDocumentoInstancia, instanciaDb.UltimaVersion.Value); var documentoInstanciaXbrlDto = JsonConvert.DeserializeObject <DocumentoInstanciaXbrlDto>(ZipUtil.UnZip(versionBD.Datos)); //if (documentoInstanciaXbrlDto.ParametrosConfiguracion == null || documentoInstanciaXbrlDto.ParametrosConfiguracion.Count == 0) //{ // documentoInstanciaXbrlDto.ParametrosConfiguracion = ObtenParametrosConfiguracion(documentoInstanciaXbrlDto, parametros); //} if (documentoInstanciaXbrlDto.Taxonomia == null) { ObtenerTaxonomia(documentoInstanciaXbrlDto); } ArchivoDocumentoInstanciaRepository.EliminaArchivosDistribucion(idDocumentoInstancia, 2); DistribucionExportarPDFLocal.EjecutarDistribucion(documentoInstanciaXbrlDto, null); }
public CmdOutput Unzip(CmdInput ci) { Zip_Unzip_Options options = ci.options as Zip_Unzip_Options; StringBuilder sb = new StringBuilder(); try { var zfiles = Common.CommFuns.ListTmpFiles(options.FileName); if (zfiles.Count == 0) { return(new CmdOutput(false, CmdRunState.FINISHEDWITHWARNING, ci.MessageId, "No file to unzip")); } foreach (var zf in zfiles) { sb.AppendLine($"Unzip {zf}:</br>"); var files = ZipUtil.UnzipFiles(File.ReadAllBytes(zf)); foreach (var f in files) { var d = Path.Combine(options.Destination, f.Key); var fd = Path.GetDirectoryName(d); if (!Directory.Exists(fd)) { Directory.CreateDirectory(fd); } File.WriteAllBytes(d, f.Value); sb.AppendLine($" {d}</br>"); } } } catch (Exception e) { sb.AppendLine($"Failed to unzip." + e.Message); return(new CmdOutput(false, CmdRunState.EXITWITHERROR, ci.MessageId, sb.ToString())); } return(new CmdOutput(true, CmdRunState.FINISHED, ci.MessageId, sb.ToString())); }
void HandleMulti(IPacketMsg packetMsg) { if (!packetMsg.IsProto) { DebugLog.WriteLine("CMClient", "HandleMulti got non-proto MsgMulti!!"); return; } var msgMulti = new ClientMsgProtobuf <CMsgMulti>(packetMsg); byte[] payload = msgMulti.Body.message_body; if (msgMulti.Body.size_unzipped > 0) { try { payload = ZipUtil.Decompress(payload); } catch (Exception ex) { DebugLog.WriteLine("CMClient", "HandleMulti encountered an exception when decompressing.\n{0}", ex.ToString()); return; } } using (var ms = new MemoryStream(payload)) using (var br = new BinaryReader(ms)) { while ((ms.Length - ms.Position) != 0) { int subSize = br.ReadInt32(); byte[] subData = br.ReadBytes(subSize); OnClientMsgReceived(GetPacketMsg(subData)); } } }
public T Deserialize <T>(string path) { var tempPath = Path.GetTempFileName(); try { ZipUtil.Unzip(path, tempPath); using (var fileStream = File.Open(tempPath, FileMode.Open)) using (var streamReader = new StreamReader(fileStream)) using (var textReader = new InternalJsonTextReader(streamReader)) { return(_jsonSerializer.Deserialize <T>(textReader)); } } finally { try { File.Delete(tempPath); } catch { } } }
// Token: 0x0600006F RID: 111 RVA: 0x000050DE File Offset: 0x000032DE private static IEnumerator UnzipFiles(string srcDir, string ext, Action finishCallback, Action <float> progressCallback) { int totalCount = 0; int couter = 0; Action onFileFinished = delegate { couter++; Action <float> progressCallback2 = progressCallback; if (progressCallback2 != null) { progressCallback2(1f * (float)couter / (float)totalCount); } }; string[] files = Directory.GetFiles(srcDir, ext); totalCount = files.Length; foreach (string filePath in files) { string dstDir = filePath.Substring(0, filePath.Length - ext.Length + 1); bool flag = Directory.Exists(dstDir); if (flag) { Directory.Delete(dstDir, true); } ZipUtil.UnZip(filePath, dstDir); File.Delete(filePath); onFileFinished(); } string[] array = null; while (totalCount > couter) { yield return(null); } finishCallback(); yield break; }
static void ProcessWork() { byte[] info = null; using (var fs = new FileStream(path_work + Path.DirectorySeparatorChar + "sce_sys" + Path.DirectorySeparatorChar + "param.sfo", FileMode.Open)) { using (var buf = new MemoryStream()) { fs.Seek(-20, SeekOrigin.End); fs.CopyTo(buf); info = buf.ToArray(); } } app_id = Encoding.ASCII.GetString(info, 0, 9); Console.WriteLine("App Id: " + app_id); Console.WriteLine("Processing..."); Directory.Delete(path_work + Path.DirectorySeparatorChar + "sce_sys" + Path.DirectorySeparatorChar + "manual", true); foreach (var d in Directory.GetDirectories(path_work)) { if (d.Contains("sce_module")) { continue; } if (d.Contains("sce_sys")) { continue; } ProcessEachFile(d); } Console.WriteLine("Packing..."); ZipUtil.CreateFromDirectory(path_work, path_mp4 + Path.DirectorySeparatorChar + "qinst_" + inst_count.ToString("X2") + ".mp4"); ++inst_count; }
/// <summary> /// Export Zipped project. /// </summary> /// <param name="sender">ToolStripMenuItem</param> /// <param name="e">EventArgs</param> private void exportZipToolStripMenuItem_Click(object sender, EventArgs e) { Project project = m_env.DataManager.CurrentProject; if (m_env.DataManager.EditCount != 0 || m_env.DataManager.CurrentProject.Info.Type != ProjectType.Project) { Util.ShowWarningDialog(MessageResources.ErrProjectUnsavedZip); return; } string dir = project.Info.ProjectPath; saveFileDialog.Filter = Constants.FilterZipFile; saveFileDialog.FileName = project.Info.Name + Constants.FileExtZip; if (saveFileDialog.ShowDialog() == DialogResult.OK) { string filename = saveFileDialog.FileName; ZipUtil zip = new ZipUtil(); try { zip.ZipFolder(filename, dir); } catch (Exception ex) { Util.ShowErrorDialog(string.Format(MessageResources.ErrSaveFile, saveFileDialog.FileName) + "\n" + ex.Message); } } }
/// <summary> /// Import Zipped project. /// </summary> /// <param name="sender">ToolStripMenuItem</param> /// <param name="e">EventArgs</param> private void importZipToolStripMenuItem_Click(object sender, EventArgs e) { openFileDialog.Filter = Constants.FilterZipFile; if (openFileDialog.ShowDialog() == DialogResult.OK) { try { // Check current project and save it. if (CloseConfirm() == ConfirmState.Canceled) return; // Close project if (!string.IsNullOrEmpty(m_env.DataManager.CurrentProjectID)) CloseProject(); // Unzip project string filename = openFileDialog.FileName; ZipUtil zip = new ZipUtil(); string projectPath = zip.UnzipProject(filename); // load project m_env.DataManager.LoadProject(projectPath); } catch (Exception ex) { Util.ShowErrorDialog(ex.Message); } } }
private void loadPackage(Package pacote) { this._pacote = pacote; this.wizardControl1.SelectedPageIndex = 1; try { groupControlInfoPackage.Visible = true; if (pacote.DataPublicacao.HasValue) { lbDtPublish.Text = pacote.DataPublicacao.Value.ToShortDateString(); labelControl6.Text = pacote.NumeroPacote; memoEditDesc.Text = pacote.Descricao; if (pacote.Anexos.Any(a => a.Extensao == ".zip")) { var firstPkg = pacote.Anexos.FirstOrDefault(); string zipName = firstPkg.FileName; //crie um temporario para receber os dados do pacote this._resourceDir = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(zipName)); FileManagerIts.DeleteDirectory(_resourceDir); FileManagerIts.CreateDirectory(_resourceDir); try { //arquivo zip string zipFile = Path.Combine(Path.GetTempPath(), zipName); //gera o zip em disco FileManagerIts.WriteBytesToFile(zipFile, firstPkg.DataFile); //extrai os dados pro temporario ZipUtil.ExtractToDirectory(zipFile, this._resourceDir); //todos os arquivos foreach (string item in FileManagerIts.ToFiles(this._resourceDir, new string[] { ".sql" }, true)) { if (item.EndsWith(".sql")) { _containsSql = true; } else if (item.EndsWith(".dll")) { _containsDll = true; } } //ja extrai o pacote e nao preciso dele no disco, os dados ja foram extraidos FileManagerIts.DeleteFile(zipFile); } catch (Exception ex) { string msg = "Falha na verificação de integridade do pacote."; XMessageIts.ExceptionMessageDetails(ex, msg); LoggerUtilIts.GenerateLogs(ex, msg); } } else { int countSql = pacote.Anexos.Count(a => a.Extensao == ".sql"); int countDll = pacote.Anexos.Count(a => a.Extensao == ".dll"); this._containsSql = countSql > 0; this._containsDll = countDll > 0; } this.pnlSql.Visible = _containsSql; if (_containsDll) { this.pnlDlls.Visible = true; detectInstallDir(); //this.groupControlInfoPackage.Location = new Point(17, 251); //this.groupControlInfoPackage.Size = new Size(806, 242); } else { this.pnlDlls.Visible = false; //this.groupControlInfoPackage.Location = new Point(17, 159); //this.groupControlInfoPackage.Size = new Size(806, 344); } wizardPage1.AllowNext = true; } else { XMessageIts.Erro("O pacote selecionado não foi publicado e não pode ser aplicado."); } } catch (Exception ex) { string msg = "O pacote de atualização informado é inválido!" + "\n\nContate o administrador para aplicar atualização."; XMessageIts.ExceptionMessageDetails(ex, msg, "Atenção"); LoggerUtilIts.GenerateLogs(ex, msg); } }
//Estou considerando que o pacote .zip é um pacote com dlls private void updateDLLs() { try { //pkg do arquivo zip var pkg = this._pacote.Anexos.FirstOrDefault(); //nome do arquivo zip string zipResource = pkg.FileName; //extraindo atualização taskLog("Iniciando atualização: " + zipResource); if (Directory.Exists(_resourceDir)) { zipResource = _resourceDir; } else { //raiz da instalação var raiz = Path.GetPathRoot(_installDir); //garante que o root de instalação e atualização sejam são iguais //a atualização sera extraida no mesmo o root "=> Volume do disco Ex: C: //Deve ser o mesmo root onde esta a instalação do programa string resourceDir = Path.Combine(Path.GetPathRoot(raiz), "ite_package_update_" + Guid.NewGuid()); //cria o temporario para receber a atualização FileManagerIts.CreateDirectory(resourceDir); //agora eu tenho um diretorio entao gere um arquivo .zip zipResource = resourceDir + "\\" + zipResource; //gera o zip em disco FileManagerIts.WriteBytesToFile(zipResource, pkg.DataFile); //extrai as atualizações pra um temporario ZipUtil.ExtractToDirectory(zipResource, resourceDir); } taskLog("Salvando instalação atual ..."); //garante que exista somente um .bak FileManagerIts.DeleteDirectory(_installDir + ".bak"); //faz a copia o da instalaçao atual FileManagerIts.DirectoryCopy(_installDir, _installDir + ".bak"); taskLog("Diretório pronto para receber atualização ..."); taskLog("Atualizando diretórios e dlls ... "); Task.Run(new Action(() => { foreach (var f in new FileManagerIts().ToFilesRecursive(_resourceDir)) { //vo mostrar so o nome o temporario q gerei nao eh importante taskLog("Atualizando: " + Path.GetFileName(f)); } })); //ilustrar dps _taskManager.UpdateSoftware(_resourceDir, _installDir); //apague o temporário FileManagerIts.DeleteDirectory(_resourceDir); } catch (Exception ex) { try { cancelation(); taskLog("Falha no pacote de atualizações"); taskLog(ex.Message); LoggerUtilIts.ShowExceptionLogs(ex, this); } catch (OperationCanceledException oc) { Console.WriteLine("Operação cancelada=> " + oc.Message); } } }
protected void btnUpload_Click(object sender, EventArgs e) { try { if (fupUploadTemp.HasFile && fupUploadTemp.PostedFile.FileName != string.Empty) { string fileName = fupUploadTemp.PostedFile.FileName; string cntType = fupUploadTemp.PostedFile.ContentType; if (fileName.Substring(fileName.Length - 3, 3).ToLower() == "zip") { string path = HttpContext.Current.Server.MapPath("~/"); string temPath = SageFrame.Common.RegisterModule.Common.TemporaryFolder; string destPath = Path.Combine(path, temPath); string downloadPath = SageFrame.Common.RegisterModule.Common.TemporaryTemplateFolder; string downloadDestPath = Path.Combine(path, downloadPath); string templateName = ParseFileNameWithoutPath(fileName.Substring(0, fileName.Length - 4)); string templateFolderPath = path + "Templates\\" + templateName; if (!Directory.Exists(templateFolderPath)) { if (!Directory.Exists(destPath)) { Directory.CreateDirectory(destPath); } string filePath = destPath + "\\" + fupUploadTemp.FileName; fupUploadTemp.SaveAs(filePath); string ExtractedPath = string.Empty; ZipUtil.UnZipFiles(filePath, destPath, ref ExtractedPath, SageFrame.Common.RegisterModule.Common.Password, SageFrame.Common.RegisterModule.Common.RemoveZipFile); DirectoryInfo temp = new DirectoryInfo(ExtractedPath); bool templateWithData = false; FileInfo[] files = temp.GetFiles(); foreach (FileInfo file in files) { if (file.Name.ToLower() == "manifest.sfe") { templateWithData = true; } } if (templateWithData == false) { if (!Directory.Exists(downloadDestPath)) { Directory.CreateDirectory(downloadDestPath); } fupUploadTemp.SaveAs(downloadDestPath + "\\" + fupUploadTemp.FileName); Directory.Move(ExtractedPath, templateFolderPath); } else { ExtractTemplate(ExtractedPath + "/" + templateName, templateName); Directory.Move(ExtractedPath + "/" + templateName + "/" + templateName, templateFolderPath); Directory.Delete(ExtractedPath, true); } ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("TemplateManagement", "TemplateInstallSuccessfully"), "", SageMessageType.Success); } else { ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("TemplateManagement", "TemplateAlreadyInstall"), "", SageMessageType.Error); } } else { ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("TemplateManagement", "InvalidTemplateZip"), "", SageMessageType.Alert); } } } catch (Exception ex) { if (ex.Message.Equals(UnexpectedEOF, StringComparison.OrdinalIgnoreCase)) { ShowMessage(SageMessageTitle.Notification.ToString(), GetSageMessage("TemplateManagement", "ZipFileIsCorrupt"), "", SageMessageType.Alert); } else { ProcessException(ex); } } }
private void Worker(object threadInfo) { string[] invalidString = { "\\", "/", ":", "*", "?", "\"", "<", ">", "|" }; IsWorking = true; var info = (RateChangerThreadInput)threadInfo; try { ThreadData.Directory = info.Path; ThreadData.OutputDir = info.OutPutDir; ThreadData.OsuNameList = Directory.GetFiles(ThreadData.Directory, "*.osu").ToList(); ThreadData.Map = new List <Beatmap>(); foreach (var cur in ThreadData.OsuNameList) { var map = Parser.LoadOsuFile(Path.Combine(ThreadData.Directory, cur)); if (map == null) { _exceptFileList.Add(Path.GetFileNameWithoutExtension(cur).Split('[')[1].Split(']')[0]); } else { ThreadData.Map.Add(map); } } ThreadData.Mp3NameList = Directory.GetFiles(ThreadData.Directory, "*.mp3").ToList(); ThreadData.Rate = info.Rate; ThreadData.Nightcore = false; ThreadData.NewOsuNameList = new List <string>(); foreach (var map in ThreadData.Map) { var tempName = map.Meta.Artist + " - " + map.Meta.Title + " (" + map.Meta.Creator + ") [" + map.Meta.Version + " x" + ThreadData.Rate + (ThreadData.Nightcore ? "_P" : "") + "].osu"; tempName = invalidString.Aggregate(tempName, (current, cur) => current.Replace(cur, "")); ThreadData.NewOsuNameList.Add(tempName); } } catch (Exception e) { IsErrorOccurred = true; Log.Error(e, "Error occurred in parsing ThreadData."); throw; } var mp3ThreadList = ThreadData.Mp3NameList.Select(cur => new Thread(() => Mp3Change(cur))).ToList(); var patternThreadList = ThreadData.Map.Select((map, i) => new Thread(() => PatternChange(map, ThreadData.NewOsuNameList[i]))).ToList(); foreach (var thread in mp3ThreadList) { thread.Start(); } foreach (var thread in patternThreadList) { thread.Start(); } foreach (var thread in mp3ThreadList) { thread.Join(); } foreach (var thread in patternThreadList) { thread.Join(); } var delFiles = new List <string>(ThreadData.NewOsuNameList); delFiles.AddRange(ThreadData.Mp3NameList.Select(cur => Path.GetFileNameWithoutExtension(cur) + "_" + ThreadData.Rate + (ThreadData.Nightcore ? "_P" : "") + ".mp3")); if (IsErrorOccurred) { foreach (var cur in delFiles) { File.Delete(Path.Combine(ThreadData.Directory, cur)); } } else { string[] exts = { ".osu", ".mp3", ".osb" }; if (info.OszChecked) { var newDir = Path.GetFileName(ThreadData.Directory) + " x" + ThreadData.Rate + (ThreadData.Nightcore ? "_P" : ""); var zipFile = newDir + ".osz"; string newPath, zipPath; foreach (var cur in invalidString) { newDir = newDir.Replace(cur, ""); zipFile = zipFile.Replace(cur, ""); } if (ThreadData.OutputDir == ThreadData.Directory) { newPath = Path.Combine(Path.GetDirectoryName(ThreadData.Directory), newDir); zipPath = Path.Combine(Path.GetDirectoryName(ThreadData.Directory), zipFile); } else { newPath = Path.Combine(ThreadData.OutputDir, newDir); zipPath = Path.Combine(ThreadData.OutputDir, zipFile); } DirectoryUtil.CopyFolder(ThreadData.Directory, newPath, exts); foreach (var cur in delFiles) { File.Move(Path.Combine(ThreadData.Directory, cur), Path.Combine(newPath, cur)); } ZipUtil.CreateFromDirectory(newPath, zipPath, true); Directory.Delete(newPath, true); _resultFile = zipPath; } else if (ThreadData.OutputDir != ThreadData.Directory) { DirectoryUtil.CopyFolder(ThreadData.Directory, ThreadData.OutputDir, exts); foreach (var cur in delFiles) { File.Move(Path.Combine(ThreadData.Directory, cur), Path.Combine(ThreadData.OutputDir, cur)); } } } IsErrorOccurred = IsWorking = false; }
//edit by czq start public static void GenZip() { ZipUtil.CreateZipFile(m_apiDir, "UnityLuaAPI.zip"); Debug.LogFormat("API 生成完毕. {0}", FilePathConst.ProjectPath + "UnityLuaAPI.zip"); }