/// <summary> /// Unpacks the update asynchronous. /// </summary> /// <param name="path">The path.</param> /// <returns>Task<System.String>.</returns> public async Task <string> UnpackUpdateAsync(string path) { if (!File.Exists(path)) { return(string.Empty); } var extractPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path)); // Cleanup path were extracting to if (Directory.Exists(extractPath)) { DiskOperations.DeleteDirectory(extractPath, true); } // Throwing exception because of this? While previously it would automatically be created Directory.CreateDirectory(extractPath); using var fileStream = File.OpenRead(path); using var reader = ArchiveFactory.Open(fileStream); var all = reader.Entries.Where(entry => !entry.IsDirectory); double total = all.Count(); double processed = 0; var lastPercentage = 0; foreach (var entry in all) { entry.WriteToDirectory(extractPath, ZipExtractionOpts.GetExtractionOptions()); processed++; var progress = GetProgressPercentage(total, processed); if (progress != lastPercentage) { await messageBus.PublishAsync(new UpdateUnpackProgressEvent(progress)); } lastPercentage = progress; } return(extractPath); }
/// <summary> /// cleanup updater as an asynchronous operation. /// </summary> private static async Task CleanupUpdaterAsync() { foreach (var path in StaticResources.GetUpdaterPath()) { if (Directory.Exists(path)) { bool cleanup = true; var settingsFileName = Path.Combine(path, Constants.UpdateSettings); if (File.Exists(settingsFileName)) { var fileInfo = new FileInfo(settingsFileName); var text = await File.ReadAllTextAsync(settingsFileName); var settings = JsonConvert.DeserializeObject <UpdateSettings>(text); // At least 72 since last update to cleanup cleanup = (settings.Updated || settings.IsInstaller) && fileInfo.LastWriteTime <= DateTime.Now.AddHours(-72); } if (cleanup) { await Task.Delay(5000); try { DiskOperations.DeleteDirectory(path, true); } catch (Exception ex) { var logger = DIResolver.Get <ILogger>(); logger.Error(ex); } } } } }
public void Test4() { ITableFilter theObj = DiskOperations.CreateTableFilterObj("TApplicationFilter.dll"); Assert.IsNotNull(theObj); Assert.IsTrue(theObj is TApplicationFilter.TApplicationFilter); }
public void SetUp() { string currentPath = Environment.CurrentDirectory; StaticConfigTable.ConnectionString = ConfigurationManager.AppSettings["ConnectionString"]; StaticConfigTable.SetRunningConfigDefault(); //构建临时数据文件夹 _TestTempDirectory = ConfigurationManager.AppSettings["TestTempDirectory"]; Assert.IsNotNull(_TestTempDirectory); _TestTempDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory); DiskOperations.CheckAndCreateDirectory(_TestTempDirectory); //拷贝配置文件 string theTransferRuleConfig = string.Format(@"{0}\..\..\TestResources\TransferConfig.xml", currentPath); Assert.IsTrue(File.Exists(theTransferRuleConfig)); CommandRunner.CopyToDirectory(theTransferRuleConfig, currentPath); //还原2个数据库用于测试 string rarFile = string.Format(@"{0}\..\..\TestResources\TestDbs.rar", currentPath); Assert.IsTrue(File.Exists(rarFile)); CommandRunner.UnRarFileToDirectory(rarFile, _TestTempDirectory, true); Assert.IsTrue(File.Exists(_TestTempDirectory + "As_BackUp.bak")); Assert.IsTrue(File.Exists(_TestTempDirectory + "Crm_BackUp.bak")); SqlCommandRunner.RestoreDbFromFile(_Db1, _TestTempDirectory, _TestTempDirectory + "As_BackUp.bak"); SqlCommandRunner.RestoreDbFromFile(_Db2, _TestTempDirectory, _TestTempDirectory + "Crm_BackUp.bak"); //mock日志记录 _MockITransferDataLog = new MockITransferDataLog(); TransferDataLogManager.SetLogInstance = _MockITransferDataLog; }
public void SetUp() { //构建临时数据文件夹 _TestTempDirectory = ConfigurationManager.AppSettings["TestTempDirectory"]; Assert.IsNotNull(_TestTempDirectory); _TestTempDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory); DiskOperations.CheckAndCreateDirectory(_TestTempDirectory); }
public void Test3() { string targetName = string.Format("{0}{1}.bak", DiskOperations.CorrectDirectory(_TestTempDirectory), _TempDbName); SqlCommandRunner.BackUpDb(_TempDbName, targetName); Assert.IsTrue(File.Exists(targetName)); CommandRunner.DeleteFile(targetName); }
/// <summary> /// Controls what happens on application startup /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override async void OnStartup(object sender, StartupEventArgs e) { //save and start the music await DiskOperations.SaveMusicToDisk(); Sounds.StartBackgroundMusic(); DisplayRootViewFor <ShellViewModel>(); }
public void Test6() { string tempOfFiles = _TestTempDirectory + "FilesTemp\\"; DiskOperations.CheckAndCreateDirectory(tempOfFiles); //指定文件夹中未含有相关的文件,将不执行任何删除 string result = DiskOperations.DelFilesFromDirectory(tempOfFiles, "nonFilesKey", "", 1); Console.WriteLine(result); Assert.AreEqual("--删除文件:未删除任何文件", result); //在指定文件夹中加入以下文件 AddFileToDirectory(tempOfFiles, "xy1.txt"); AddFileToDirectory(tempOfFiles, "xy2.txt"); AddFileToDirectory(tempOfFiles, "xy3.txt"); AddFileToDirectory(tempOfFiles, "notReleatedFile.txt"); //未匹配Key的文件不会删除 string result1 = DiskOperations.DelFilesFromDirectory(tempOfFiles, "nonFilesKey", "", 1); Console.WriteLine(result1); Assert.AreEqual("--删除文件:未删除任何文件", result); Assert.IsTrue(File.Exists(tempOfFiles + "xy1.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "xy2.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "xy3.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "notReleatedFile.txt")); //匹配Key,未指定受保护对象,将会把最早创建的xy1删除 string result2 = DiskOperations.DelFilesFromDirectory(tempOfFiles, "xy", "", 2); Console.WriteLine(result2); Assert.AreEqual(@"--删除文件:C:\TestTempData\FilesTemp\xy1.txt", result2); Assert.IsTrue(File.Exists(tempOfFiles + "xy2.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "xy3.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "notReleatedFile.txt")); //匹配Key,但是限制了文件夹内含有的数量,不会删除任何对象 string result3 = DiskOperations.DelFilesFromDirectory(tempOfFiles, "xy", "", 2); Console.WriteLine(result3); Assert.AreEqual("--删除文件:未删除任何文件", result3); Assert.IsTrue(File.Exists(tempOfFiles + "xy2.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "xy3.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "notReleatedFile.txt")); //匹配Key,指定受保护对象(xy2.txt),将会把最晚创建的xy3删除 string result4 = DiskOperations.DelFilesFromDirectory(tempOfFiles, "xy", tempOfFiles + "xy2.txt", 1); Console.WriteLine(result4); Assert.AreEqual(@"--删除文件:C:\TestTempData\FilesTemp\xy3.txt", result4); Assert.IsTrue(File.Exists(tempOfFiles + "xy2.txt")); Assert.IsTrue(File.Exists(tempOfFiles + "notReleatedFile.txt")); //清理文件夹 CommandRunner.CleanUpDirectory(tempOfFiles); }
/// <summary> /// Gets the last fatal exception. /// </summary> /// <returns>System.String.</returns> public string GetLastFatalException() { var fileName = GetLastExceptionFileName(new LogEventInfo(LogLevel.Info, string.Empty, string.Empty)); if (File.Exists(fileName)) { var data = File.ReadAllText(fileName); DiskOperations.DeleteFile(fileName); return(data); } return(string.Empty); }
/// <summary> /// Clears the definition asynchronous. /// </summary> /// <param name="storagePath">The storage path.</param> /// <param name="game">The game.</param> /// <returns>Task<System.Boolean>.</returns> public virtual Task <bool> ClearDefinitionAsync(string storagePath, IGame game) { storagePath = ResolveStoragePath(storagePath); var fullPath = Path.Combine(storagePath, game.Type); if (Directory.Exists(fullPath)) { DiskOperations.DeleteDirectory(fullPath, true); return(Task.FromResult(true)); } return(Task.FromResult(false)); }
public void Test2() { DiskOperations.PrepareForRestore(); Assert.AreEqual(@"C:\DataTemp\ForRestore\", DiskOperations.DataTemp_ForRestoreDirectory); Assert.AreEqual(@"C:\ShiXinTechDbBackUp\ForRestore\", DiskOperations.DbBackUp_ForRestoreDirectory); Assert.AreEqual(@"C:\DataTemp\", DiskOperations.TempDirectory); Assert.IsTrue(Directory.Exists(@"C:\DataTemp\")); Assert.IsTrue(Directory.Exists(@"C:\DataTemp\ForRestore")); Assert.IsTrue(Directory.Exists(@"C:\ShiXinTechDbBackUp\ForRestore")); }
public void SetUp() { StaticConfigTable.BackUpDirectory = @"C:\ShiXinTechDbBackUp"; StaticConfigTable.DownloadFilesDirectory = @"C:\ShiXinTech\DownLoadFiles\"; StaticConfigTable.TempDirectory = @"C:\DataTemp"; //构建临时数据文件夹 _TestTempDirectory = ConfigurationManager.AppSettings["TestTempDirectory"]; Assert.IsNotNull(_TestTempDirectory); _TestTempDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory); DiskOperations.CheckAndCreateDirectory(_TestTempDirectory); }
public void Test1() { DiskOperations.PrepareForBackUp(); Assert.AreEqual(@"C:\DataTemp\ForBackUp\", DiskOperations.DataTemp_ForBackUpDirectory); Assert.AreEqual(@"C:\ShiXinTechDbBackUp\ForBackUp\", DiskOperations.DbBackUp_ForBackUpDirectory); Assert.AreEqual(@"C:\ShiXinTech\DownLoadFiles\", DiskOperations.DownLoadDirectory); Assert.AreEqual(@"C:\DataTemp\", DiskOperations.TempDirectory); Assert.IsTrue(Directory.Exists(@"C:\DataTemp\")); Assert.IsTrue(Directory.Exists(@"C:\DataTemp\ForBackUp\")); Assert.IsTrue(Directory.Exists(@"C:\ShiXinTechDbBackUp\ForBackUp\")); Assert.IsTrue(Directory.Exists(@"C:\ShiXinTech\DownLoadFiles\")); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { StaticConfigTable.ConfigFilePath = HttpContext.Current.Request.PhysicalApplicationPath + "DataTransferConfig.xml"; StaticConfigTable.ExpandDllPath = HttpContext.Current.Request.PhysicalApplicationPath + "bin"; StaticConfigTable.UploadFileDirectory = HttpContext.Current.Request.PhysicalApplicationPath + "UpLoadDirectory\\"; StaticConfigTable.Log4NetConfigPath = HttpContext.Current.Request.PhysicalApplicationPath + "DataTransferConfig.xml"; DiskOperations.CheckAndCreateDirectory(StaticConfigTable.UploadFileDirectory); Timer1.Enabled = false; } lblMessage.Text = string.Empty; Message.Visible = false; }
public void SetUp() { //构建临时数据文件夹 _TestTempDirectory = ConfigurationManager.AppSettings["TestTempDirectory"]; Assert.IsNotNull(_TestTempDirectory); _TestTempDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory); DiskOperations.CheckAndCreateDirectory(_TestTempDirectory); StaticConfigTable.BackUpDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory) + "TestTransferConfig"; StaticConfigTable.DownloadFilesDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory) + "TestDownLoadFiles"; StaticConfigTable.TempDirectory = DiskOperations.CorrectDirectory(_TestTempDirectory) + "Temps"; DiskOperations.PrepareForBackUp(); DiskOperations.PrepareForRestore(); }
public void SetUp() { //配置文件读取 _ConnectionString = ConfigurationManager.AppSettings["ConnectionString"]; _TestTempDirectory = ConfigurationManager.AppSettings["TestTempDirectory"]; Assert.IsNotNull(_ConnectionString); Assert.IsNotNull(_TestTempDirectory); StaticConfigTable.ConnectionString = _ConnectionString; DiskOperations.CheckAndCreateDirectory(DiskOperations.CorrectDirectory(_TestTempDirectory)); //数据库资源路径 string currentPath = Environment.CurrentDirectory; string theBackUpDb = string.Format(@"{0}\..\..\TestResources\TestApplicationFilterDb.bak", currentPath); Assert.IsTrue(File.Exists(theBackUpDb)); //开始构建1数据库 SqlCommandRunner.RestoreDbFromFile(_TempDbName, DiskOperations.CorrectDirectory(_TestTempDirectory), theBackUpDb); SqlCommandRunner.RestoreDbFromFile(_TempOtherDbName, DiskOperations.CorrectDirectory(_TestTempDirectory), theBackUpDb); }
/// <summary> /// Deletes this instance. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool Delete() { try { if (System.IO.File.Exists(path)) { DiskOperations.DeleteFile(path); return(true); } } catch (Exception ex) { if (logger != null) { logger.Error(ex); } } return(false); }
public void Test3() { //测试DownLoadFiles文件夹的配置 StaticConfigTable.DownloadFilesDirectory = @"C:\DataTemp\DownLoadFiles\"; try { DiskOperations.PrepareForBackUp(); Assert.Fail(); } catch (ApplicationException ae) { Assert.AreEqual("当前数据迁移的配置文件中以下配置有问题,因为TempDirectory文件夹会被程序清空造成重要数据丢失,无法在TempDirectory文件夹下配置BackUpDirectory或者DownloadFilesDirectory", ae.Message); } //测试BackUp文件夹的配置 StaticConfigTable.DownloadFilesDirectory = @"C:\ShiXinTech\DownLoadFiles\"; StaticConfigTable.BackUpDirectory = @"C:\DataTemp\DataBackUp"; try { DiskOperations.PrepareForBackUp(); Assert.Fail(); } catch (ApplicationException ae) { Assert.AreEqual("当前数据迁移的配置文件中以下配置有问题,因为TempDirectory文件夹会被程序清空造成重要数据丢失,无法在TempDirectory文件夹下配置BackUpDirectory或者DownloadFilesDirectory", ae.Message); } try { DiskOperations.PrepareForRestore(); Assert.Fail(); } catch (ApplicationException ae) { Assert.AreEqual("当前数据迁移的配置文件中以下配置有问题,因为TempDirectory文件夹会被程序清空造成重要数据丢失,无法在TempDirectory文件夹下配置BackUpDirectory或者DownloadFilesDirectory", ae.Message); } //正常的设置 StaticConfigTable.BackUpDirectory = @"C:\ShiXinTechDbBackUp"; DiskOperations.PrepareForBackUp(); DiskOperations.PrepareForRestore(); }
public void Test5() { string targetConfigName = string.Format("{0}Config.txt", _TestTempDirectory); //写入 List <string> theConfigs = new List <string>(); theConfigs.Add("RuleName =It's a ruleName Test"); theConfigs.Add("Parameter = (1999,1,1)-(2008,1,1)"); DiskOperations.WriteLinesToFile(targetConfigName, theConfigs); Assert.IsTrue(File.Exists(targetConfigName)); //读取 List <string> theReadConfigs = DiskOperations.ReadLinesFromFile(targetConfigName); Assert.AreEqual(theConfigs.Count, theReadConfigs.Count); for (int i = 0; i < theReadConfigs.Count; i++) { Assert.AreEqual(theConfigs[i], theReadConfigs[i]); } //清理 CommandRunner.CleanUpDirectory(_TestTempDirectory); }
public void Test4() { const string fileName = "testFile.txt"; string targetFile = _TestTempDirectory + "t e s t.rar"; StreamWriter sw = new StreamWriter(_TestTempDirectory + fileName, false); sw.Write("测试文件,随意删除,不过见到此文件就说明垃圾清理工作没有做好-_-!"); sw.Close(); CommandRunner.RarDirectoryToFile(targetFile, _TestTempDirectory); Assert.IsTrue(File.Exists(targetFile)); string tempDir = DiskOperations.CorrectDirectory(_TestTempDirectory) + "T e m p s" + "\\"; Assert.IsTrue(!File.Exists(tempDir + fileName)); DiskOperations.CheckAndCreateDirectory(tempDir); CommandRunner.UnRarFileToDirectory(targetFile, tempDir, true); Assert.IsTrue(File.Exists(tempDir + fileName)); CommandRunner.CleanUpDirectory(tempDir); CommandRunner.CleanUpDirectory(_TestTempDirectory); }
public void Test2() { const string fileName = "testFile.txt"; const string tempDirectoryName = "Temps"; string completeDir = DiskOperations.CorrectDirectory(_TestTempDirectory) + tempDirectoryName + "\\"; DiskOperations.CheckAndCreateDirectory(completeDir); //先构建一个文件 StreamWriter sw = new StreamWriter(_TestTempDirectory + fileName, false); sw.Write("测试文件,随意删除,不过见到此文件就说明垃圾清理工作没有做好-_-!"); sw.Close(); //拷贝 CommandRunner.CopyToDirectory(_TestTempDirectory + fileName, completeDir); Assert.IsTrue(File.Exists(completeDir + fileName)); //清理 CommandRunner.CleanUpDirectory(_TestTempDirectory); CommandRunner.DeleteFile(completeDir + fileName); Assert.IsTrue(!File.Exists(completeDir + fileName)); }
/// <summary> /// write version as an asynchronous operation. /// </summary> /// <param name="storagePath">The storage path.</param> /// <param name="game">The game.</param> /// <param name="gameVersion">The game version.</param> /// <param name="cacheVersion">The cache version.</param> /// <returns>System.Threading.Tasks.Task<bool>.</returns> public virtual async Task <bool> WriteVersionAsync(string storagePath, IGame game, IEnumerable <string> gameVersion, int cacheVersion) { storagePath = ResolveStoragePath(storagePath); var gameVersionFullPath = Path.Combine(storagePath, game.Type, GameVersionFile); var cacheVersionFullPath = Path.Combine(storagePath, game.Type, CacheVersionFile); if (!Directory.Exists(Path.GetDirectoryName(gameVersionFullPath))) { Directory.CreateDirectory(Path.GetDirectoryName(gameVersionFullPath)); } if (File.Exists(gameVersionFullPath)) { DiskOperations.DeleteFile(gameVersionFullPath); } if (File.Exists(cacheVersionFullPath)) { DiskOperations.DeleteFile(cacheVersionFullPath); } await File.WriteAllTextAsync(gameVersionFullPath, string.Join(Environment.NewLine, gameVersion)); await File.WriteAllTextAsync(cacheVersionFullPath, cacheVersion.ToString()); return(false); }
/// <summary> /// Saves the definitions asynchronous. /// </summary> /// <param name="storagePath">The storage path.</param> /// <param name="game">The game.</param> /// <param name="definitions">The definitions.</param> /// <returns>Task<System.Boolean>.</returns> /// <exception cref="ArgumentException">Definitions types differ.</exception> public virtual async Task <bool> SaveDefinitionsAsync(string storagePath, IGame game, IEnumerable <IDefinition> definitions) { storagePath = ResolveStoragePath(storagePath); if (definitions.GroupBy(p => p.ParentDirectory).Count() > 1) { throw new ArgumentException("Definitions types differ."); } if (definitions == null || !definitions.Any()) { return(false); } var path = SanitizePath(definitions.FirstOrDefault().ParentDirectory); var fullPath = Path.Combine(storagePath, game.Type, path); if (File.Exists(fullPath)) { DiskOperations.DeleteFile(fullPath); } var json = JsonDISerializer.Serialize(definitions.ToList()); var bytes = Encoding.UTF8.GetBytes(json); using var source = new MemoryStream(bytes); using var destination = new MemoryStream(); using var compress = new DeflateStream(destination, CompressionLevel.Fastest, true); await source.CopyToAsync(compress); await compress.FlushAsync(); if (!Directory.Exists(Path.GetDirectoryName(fullPath))) { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); } await File.WriteAllBytesAsync(fullPath, destination.ToArray()); return(true); }
/// <summary> /// Controls what happens on application close /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected override async void OnExit(object sender, EventArgs e) { //stop and delete the music Sounds.StopBackgroundMusic(); await DiskOperations.DeleteMusicFromDisk(); }
/// <summary> /// Imports the internal. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="importInstance">if set to <c>true</c> [import instance].</param> /// <param name="collectionImportResult">The collection import result.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private bool ImportInternal(ModCollectionExporterParams parameters, bool importInstance, out ICollectionImportResult collectionImportResult) { ICollectionImportResult importResult = null; if (importInstance) { importResult = DIResolver.Get <ICollectionImportResult>(); } if (!importInstance) { if (Directory.Exists(parameters.ModDirectory)) { DiskOperations.DeleteDirectory(parameters.ModDirectory, true); } } var result = false; int getTotalFileCount() { var count = 0; using var fileStream = File.OpenRead(parameters.File); using var reader = ReaderFactory.Open(fileStream); while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { count++; } } fileStream.Close(); fileStream.Dispose(); return(count); } void parseUsingReaderFactory() { double total = getTotalFileCount(); using var fileStream = File.OpenRead(parameters.File); using var reader = ReaderFactory.Open(fileStream); double processed = 0; double previousProgress = 0; while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { var relativePath = reader.Entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar); if (reader.Entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase)) { if (importInstance) { using var entryStream = reader.OpenEntryStream(); using var memoryStream = new MemoryStream(); entryStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using var streamReader = new StreamReader(memoryStream, true); var text = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); var model = JsonDISerializer.Deserialize <IModCollection>(text); mapper.Map(model, importResult); importResult.ModNames = model.ModNames; importResult.Descriptors = model.Mods; result = true; break; } } else { if (!importInstance) { var exportFileName = Path.Combine(relativePath.StartsWith(Common.Constants.ModExportPath + Path.DirectorySeparatorChar) ? parameters.ExportModDirectory : parameters.ModDirectory, relativePath.Replace(Common.Constants.ModExportPath + Path.DirectorySeparatorChar, string.Empty)); if (!Directory.Exists(Path.GetDirectoryName(exportFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(exportFileName)); } reader.WriteEntryToFile(exportFileName, ZipExtractionOpts.GetExtractionOptions()); } } processed++; var perc = GetProgressPercentage(total, processed, 100); if (perc != previousProgress) { messageBus.Publish(new ModExportProgressEvent(perc)); previousProgress = perc; } } } } void parseUsingArchiveFactory() { using var fileStream = File.OpenRead(parameters.File); using var reader = ArchiveFactory.Open(fileStream); var entries = reader.Entries.Where(entry => !entry.IsDirectory); double total = !importInstance?entries.Count() : 1; double processed = 0; double previousProgress = 0; foreach (var entry in entries) { var relativePath = entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar); if (entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase)) { if (importInstance) { using var entryStream = entry.OpenEntryStream(); using var memoryStream = new MemoryStream(); entryStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using var streamReader = new StreamReader(memoryStream, true); var text = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); var model = JsonDISerializer.Deserialize <IModCollection>(text); mapper.Map(model, importResult); importResult.ModNames = model.ModNames; importResult.Descriptors = model.Mods; result = true; break; } } else { if (!importInstance) { var exportFileName = Path.Combine(relativePath.StartsWith(Common.Constants.ModExportPath + Path.DirectorySeparatorChar) ? parameters.ExportModDirectory : parameters.ModDirectory, relativePath.Replace(Common.Constants.ModExportPath + Path.DirectorySeparatorChar, string.Empty)); if (!Directory.Exists(Path.GetDirectoryName(exportFileName))) { Directory.CreateDirectory(Path.GetDirectoryName(exportFileName)); } entry.WriteToFile(exportFileName, ZipExtractionOpts.GetExtractionOptions()); } } processed++; var perc = GetProgressPercentage(total, processed, 100); if (perc != previousProgress) { messageBus.Publish(new ModExportProgressEvent(perc)); previousProgress = perc; } } } try { parseUsingArchiveFactory(); } catch (Exception ex) { logger.Error(ex); result = false; parseUsingReaderFactory(); } collectionImportResult = importResult; return(!importInstance || result); }
/// <summary> /// Imports the internal. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="importInstance">if set to <c>true</c> [import instance].</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> private bool ImportInternal(ModCollectionExporterParams parameters, bool importInstance) { if (!importInstance) { if (Directory.Exists(parameters.ModDirectory)) { DiskOperations.DeleteDirectory(parameters.ModDirectory, true); } } var result = false; void parseUsingReaderFactory() { using var fileStream = File.OpenRead(parameters.File); using var reader = ReaderFactory.Open(fileStream); while (reader.MoveToNextEntry()) { if (!reader.Entry.IsDirectory) { var relativePath = reader.Entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar); if (reader.Entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase)) { if (importInstance) { using var entryStream = reader.OpenEntryStream(); using var memoryStream = new MemoryStream(); entryStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using var streamReader = new StreamReader(memoryStream, true); var text = streamReader.ReadToEnd(); streamReader.Close(); JsonConvert.PopulateObject(text, parameters.Mod); result = true; break; } } else { reader.WriteEntryToDirectory(parameters.ModDirectory, ZipExtractionOpts.GetExtractionOptions()); } } } } void parseUsingArchiveFactory() { using var fileStream = File.OpenRead(parameters.File); using var reader = ArchiveFactory.Open(fileStream); foreach (var entry in reader.Entries.Where(entry => !entry.IsDirectory)) { var relativePath = entry.Key.StandardizeDirectorySeparator().Trim(Path.DirectorySeparatorChar); if (entry.Key.Equals(Common.Constants.ExportedModContentId, StringComparison.OrdinalIgnoreCase)) { if (importInstance) { using var entryStream = entry.OpenEntryStream(); using var memoryStream = new MemoryStream(); entryStream.CopyTo(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); using var streamReader = new StreamReader(memoryStream, true); var text = streamReader.ReadToEnd(); streamReader.Close(); JsonConvert.PopulateObject(text, parameters.Mod); result = true; break; } } else { entry.WriteToDirectory(parameters.ModDirectory, ZipExtractionOpts.GetExtractionOptions()); } } } try { parseUsingArchiveFactory(); } catch (Exception ex) { logger.Error(ex); result = false; parseUsingReaderFactory(); } return(!importInstance || result); }