public IEnumerable <string> GetFiles(string path, string filter, MySearchOption searchOption) { MyZipArchive zipFile = TryDoZipAction(path, TryGetZipArchive, null); string subpath = ""; if (searchOption == MySearchOption.TopDirectoryOnly) { subpath = TryDoZipAction(path, TryGetSubpath, null); } if (zipFile != null) { string pattern = Regex.Escape(filter).Replace(@"\*", ".*").Replace(@"\?", "."); pattern += "$"; foreach (var fileName in zipFile.FileNames) { if (searchOption == MySearchOption.TopDirectoryOnly) { if (fileName.Count((x) => x == '\\') != subpath.Count((x) => x == '\\') + 1) { continue; } } if (Regex.IsMatch(fileName, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { yield return(Path.Combine(zipFile.ZipPath, fileName)); } } zipFile.Dispose(); } }
public static MyObjectBuilder_Definitions LoadWorkshopPrefab(string archive, ulong?publishedItemId) { if (!File.Exists(archive) || publishedItemId == null) { return(null); } var subItem = MyGuiBlueprintScreen.m_subscribedItemsList.Find(item => item.PublishedFileId == publishedItemId); if (subItem == null) { return(null); } var extracted = MyZipArchive.OpenOnFile(archive); var stream = extracted.GetFile("bp.sbc").GetStream(); if (stream == null) { return(null); } MyObjectBuilder_Definitions objectBuilder = null; var success = MyObjectBuilderSerializer.DeserializeXML(stream, out objectBuilder); stream.Close(); extracted.Dispose(); if (success) { objectBuilder.ShipBlueprints[0].Description = subItem.Description; objectBuilder.ShipBlueprints[0].CubeGrids[0].DisplayName = subItem.Title; return(objectBuilder); } return(null); }
private Image TryGetPlanetTexture(string name, MyModContext context, string p, out string fullPath) { bool flag = false; string text1 = name + p; name = text1; fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".png"; if (!context.IsBaseGame) { if (MyFileSystem.FileExists(fullPath)) { flag = true; } else { fullPath = Path.Combine(context.ModPathData, "PlanetDataFiles", name) + ".dds"; if (MyFileSystem.FileExists(fullPath)) { flag = true; } } } if (!flag) { string str = Path.Combine(MyFileSystem.ContentPath, PlanetDataFilesPath); fullPath = Path.Combine(str, name) + ".png"; if (!MyFileSystem.FileExists(fullPath)) { fullPath = Path.Combine(str, name) + ".dds"; if (!MyFileSystem.FileExists(fullPath)) { return(null); } } } if (fullPath.Contains(MyWorkshop.WorkshopModSuffix)) { string path = fullPath.Substring(0, fullPath.IndexOf(MyWorkshop.WorkshopModSuffix) + MyWorkshop.WorkshopModSuffix.Length); string str3 = fullPath.Replace(path + @"\", ""); MyZipArchive archive = MyZipArchive.OpenOnFile(path, FileMode.Open, FileAccess.Read, FileShare.Read, false); try { return(Image.Load(archive.GetFile(str3).GetStream(FileMode.Open, FileAccess.Read))); } catch (Exception) { MyLog.Default.Error("Failed to load existing " + p + " file mod archive. " + fullPath, Array.Empty <object>()); return(null); } finally { if (archive != null) { archive.Dispose(); } } } return(Image.Load(fullPath)); }
public void UnzipPlugin(string zipName) { if (!File.Exists(zipName)) { return; } MyZipArchive.ExtractToDirectory(zipName, _pluginManager.PluginDir); }
bool FileExistsInZip(string zipFile, string subpath) { var arc = MyZipArchive.OpenOnFile(zipFile); try { return(arc.FileExists(subpath)); } finally { arc.Dispose(); } }
public void ZipArchiveAddFiles() { // arrange MyZipArchive zipArchive = Factory.CreateZipArchive(Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".zip")); MyFolder folder = Factory.CreateFolder(Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()))); string content = "S);PFE_NWaf9fAk"; MyFile file1 = Factory.CreateFile(folder.FullPath + "\\document.doc"); file1.FileAppendAllText(content); MyFile file2 = Factory.CreateFile(folder.FullPath + "\\documentx.docx"); file2.FileAppendAllText(content); MyFile file3 = Factory.CreateFile(folder.FullPath + "\\document.html"); file3.FileAppendAllText(content); MyFile file4 = Factory.CreateFile(folder.FullPath + "\\document.dot"); file4.FileAppendAllText(content); MyFile file5 = Factory.CreateFile(folder.FullPath + "\\page.doc"); file5.FileAppendAllText(content); MyFile file6 = Factory.CreateFile(folder.FullPath + "\\image.jpg"); file6.FileAppendAllText(content); HashSet <string> paths = new HashSet <string>(); paths.Add(file1.Name); paths.Add(file2.Name); paths.Add(file3.Name); paths.Add(file4.Name); paths.Add(file5.Name); paths.Add(file6.Name); // act folder.CopyToDirectory(zipArchive); var dirs = zipArchive.DirectoryGetFolders; if (dirs.Count != 1) { Assert.Fail("There is " + dirs.Count + " folders. Expected 1."); } var files = dirs[0].DirectoryGetFiles; if (files.Count != 6) { Assert.Fail("There is " + files.Count + " files in " + dirs[0].FullPath + ". Expected 6."); } foreach (var file in files) { if (!paths.Contains(file.Name)) { Assert.Fail(dirs[0].FullPath + "does not contain " + file.Name + "."); } else { paths.Remove(file.Name); } } // удаляем используемые entry folder.Delete(); zipArchive.Delete(); // assert Assert.IsTrue(paths.Count == 0); }
private Stream TryOpen(string zipFile, string subpath) { var arc = MyZipArchive.OpenOnFile(zipFile); try { return(arc.FileExists(subpath) ? new MyStreamWrapper(arc.GetFile(subpath).GetStream(), arc) : null); } catch { arc.Dispose(); return(null); } }
private MyZipArchive TryGetZipArchive(string zipFile, string subpath) { var arc = MyZipArchive.OpenOnFile(zipFile); try { return(arc); } catch { arc.Dispose(); return(null); } }
public void ExtractSandboxFromZip() { const string filename = @".\TestAssets\Sample World.sbw"; MyObjectBuilder_Checkpoint checkpoint; using (MyZipArchive archive = MyZipArchive.OpenOnFile(filename)) { MyZipFileInfo fileInfo = archive.GetFile(SpaceEngineersConsts.SandBoxCheckpointFilename); checkpoint = SpaceEngineersApi.ReadSpaceEngineersFile <MyObjectBuilder_Checkpoint>(fileInfo.GetStream()); } Assert.AreEqual("Quad Scissor Doors", checkpoint.SessionName, "Checkpoint SessionName must match!"); }
public void ExtractZipFileToFolder() { const string filename = @".\TestAssets\Sample World.sbw"; const string folder = @".\TestOutput\Sample World"; Assert.IsTrue(File.Exists(filename), "Source file must exist"); ZipTools.MakeClearDirectory(folder); // Keen's API doesn't know difference between file and folder. MyZipArchive.ExtractToDirectory(filename, folder); Assert.IsTrue(File.Exists(Path.Combine(folder, SpaceEngineersConsts.SandBoxCheckpointFilename)), "Destination file must exist"); }
bool DirectoryExistsInZip(string zipFile, string subpath) { var arc = MyZipArchive.OpenOnFile(zipFile); try { // Root exists when archive can be opened return(subpath == String.Empty ? true : arc.DirectoryExists(subpath + "/")); } finally { arc.Dispose(); } }
public void ExtractZipAndRepack() { const string filename = @".\TestAssets\Sample World.sbw"; const string folder = @".\TestOutput\Sample World Repack"; ZipTools.MakeClearDirectory(folder); // Keen's API doesn't know difference between file and folder. MyZipArchive.ExtractToDirectory(filename, folder); const string newFilename = @".\TestOutput\New World.sbw"; MyZipArchive.CreateFromDirectory(folder, newFilename, DeflateOptionEnum.Maximum, false); Assert.IsTrue(File.Exists(newFilename), "Destination file must exist"); }
public bool Extract() { var sanitizedTitle = Path.GetInvalidFileNameChars().Aggregate(Title, (current, c) => current.Replace(c.ToString(), "_")); var dest = Path.Combine(m_extractPath, string.Format("{0} {1} ({2})", Constants.SEWT_Prefix, sanitizedTitle, m_modId.ToString())); MySandboxGame.Log.WriteLineAndConsole(string.Format("Extracting item: '{0}' to: \"{1}\"", m_title, dest)); if (Directory.Exists(m_modPath)) { MyFileSystem.CopyAll(m_modPath, dest); } else { MyZipArchive.ExtractToDirectory(m_modPath, dest); } return(true); }
public IEnumerable <string> GetFiles(string path, string filter, MySearchOption searchOption) { MyZipArchive zipFile = TryDoZipAction(path, TryGetZipArchive, null); string subpath = ""; if (searchOption == MySearchOption.TopDirectoryOnly) { subpath = TryDoZipAction(path, TryGetSubpath, null); } if (zipFile != null) { #if XB1 System.Diagnostics.Debug.Assert(false, "TODO for XB1."); if (filter == "hgdshfjghjdsghj") { yield return(""); } #else // !XB1 string pattern = Regex.Escape(filter).Replace(@"\*", ".*").Replace(@"\?", "."); pattern += "$"; foreach (var fileName in zipFile.FileNames) { if (searchOption == MySearchOption.TopDirectoryOnly) { if (fileName.Count((x) => x == '\\') != subpath.Count((x) => x == '\\') + 1) { continue; } } if (Regex.IsMatch(fileName, pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) { yield return(Path.Combine(zipFile.ZipPath, fileName)); } } #endif // !XB1 zipFile.Dispose(); } }
public bool Extract() { string ext = ".sbm"; if (m_tags.Contains(MySteamWorkshop.WORKSHOP_MOD_TAG)) { ext = ".sbm"; } else if (m_tags.Contains(MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG)) { ext = ".sbb"; } else if (m_tags.Contains(WorkshopType.IngameScript.ToString())) { ext = ".sbs"; } else if (m_tags.Contains(MySteamWorkshop.WORKSHOP_WORLD_TAG)) { ext = ".sbw"; } else if (m_tags.Contains(MySteamWorkshop.WORKSHOP_SCENARIO_TAG)) { ext = ".sbs"; } var sanitizedTitle = Path.GetInvalidFileNameChars().Aggregate(Title, (current, c) => current.Replace(c.ToString(), "_")); var source = Path.Combine(m_modPath, m_modId.ToString() + ext); if (!File.Exists(source)) { source = Path.Combine(m_modPath, @"..\workshop", m_modId.ToString() + ext); } var dest = Path.Combine(m_modPath, string.Format("{0} {1} ({2})", Constants.SEWT_Prefix, sanitizedTitle, m_modId.ToString())); MySandboxGame.Log.WriteLineAndConsole(string.Format("Extracting mod: '{0}' to: \"{1}\"", sanitizedTitle, dest)); MyZipArchive.ExtractToDirectory(source, dest); return(true); }
public void AddFileToZipArchiveAndUnzip() { // arrange MyZipArchive zipArchive = Factory.CreateZipArchive(Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".zip")); MyFile file = Factory.CreateFile(Path.Combine (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Path.GetRandomFileName())); MyFolder tempFolder = Factory.GetSpecialFolder(Environment.SpecialFolder.ApplicationData); // act file.FileAppendAllText("content1"); file.MoveToDirectory(zipArchive); //перемещаем файл в архив if (file.Exists) { Assert.Fail("File " + file.FullPath + "is moved, but Exists is true!"); } var files = zipArchive.DirectoryGetFiles; if (files.Count != 1) { Assert.Fail("Archive contains " + files.Count + " files, expected 1!"); } files[0].CopyToDirectory(tempFolder); //копируем файл из архива на прежнее место if (!file.Exists) { Assert.Fail("File " + file.FullPath + "is unzipped, but Exists is false!"); } string fileContent = file.FileReadAllLines()[0]; // удаляем все файлы zipArchive.Delete(); file.Delete(); // assert Assert.AreEqual("content1", fileContent); }
void ExtractWorkShopItems() { ProfilerShort.Begin("Blueprint screen - Extracting bluepritns"); if (!Directory.Exists(m_workshopBlueprintFolder)) { Directory.CreateDirectory(m_workshopBlueprintFolder); } var downloadedMods = Directory.GetFiles(m_workshopBlueprintFolder); foreach (var mod in downloadedMods) { var fileName = Path.GetFileNameWithoutExtension(mod); var id = ulong.Parse(fileName); if (!m_subscribedItemsList.Any(item => item.PublishedFileId == id)) { File.Delete(mod); } } var tempPath = Path.Combine(m_workshopBlueprintFolder, "temp"); if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } var tempDir = Directory.CreateDirectory(tempPath); foreach (var subItem in m_subscribedItemsList) { if (downloadedMods.Any(item => item.Contains(subItem.PublishedFileId.ToString()))) { string archive = Array.Find(downloadedMods, item => item.Contains(subItem.PublishedFileId.ToString())); var extractPath = Path.Combine(tempDir.FullName, subItem.PublishedFileId.ToString()); if (!File.Exists(extractPath)) { Directory.CreateDirectory(extractPath); var extracted = MyZipArchive.OpenOnFile(archive); var modInfo = new MyObjectBuilder_ModInfo(); modInfo.SubtypeName = subItem.Title; modInfo.WorkshopId = subItem.PublishedFileId; modInfo.SteamIDOwner = subItem.SteamIDOwner; var infoFile = Path.Combine(m_workshopBlueprintFolder, "temp", subItem.PublishedFileId.ToString(), "info.temp"); if (File.Exists(infoFile)) { File.Delete(infoFile); } var infoSuccess = MyObjectBuilderSerializer.SerializeXML(infoFile, false, modInfo); if (extracted.FileExists("thumb.png")) { var stream = extracted.GetFile("thumb.png").GetStream(); if (stream != null) { using (var file = File.Create(Path.Combine(extractPath, "thumb.png"))) { stream.CopyTo(file); } } stream.Close(); } extracted.Dispose(); var info = new MyBlueprintItemInfo(MyBlueprintTypeEnum.STEAM, subItem.PublishedFileId); var listItem = new MyGuiControlListbox.Item(text: new StringBuilder(subItem.Title), toolTip: subItem.Title, icon: MyGuiConstants.TEXTURE_ICON_MODS_WORKSHOP.Normal, userData: info); var itemIndex = m_blueprintList.Items.FindIndex(item => ((item.UserData as MyBlueprintItemInfo).PublishedItemId == (listItem.UserData as MyBlueprintItemInfo).PublishedItemId) && (item.UserData as MyBlueprintItemInfo).Type == MyBlueprintTypeEnum.STEAM); if (itemIndex == -1) { m_blueprintList.Add(listItem); } } } } ProfilerShort.End(); }
// Starts new session with campaign data public void LoadSessionFromActiveCampaign(string relativePath, Action afterLoad = null, string campaignDirectoryName = null) { var savePath = relativePath; string absolutePath; // >> WORLD FILE OPERATIONS // Find the existing file in order of modded content to vanilla if (m_activeCampaign.IsVanilla || m_activeCampaign.IsDebug) { absolutePath = Path.Combine(MyFileSystem.ContentPath, savePath); if (!MyFileSystem.FileExists(absolutePath)) { MySandboxGame.Log.WriteLine("ERROR: Missing vanilla world file in campaign: " + m_activeCampaignName); Debug.Fail("ERROR: Missing vanilla world file in campaign: " + m_activeCampaignName); return; } } else { // Modded content absolutePath = Path.Combine(m_activeCampaign.ModFolderPath, savePath); // try finding respective vanilla file if the file does not exist if (!MyFileSystem.FileExists(absolutePath)) { absolutePath = Path.Combine(MyFileSystem.ContentPath, savePath); if (!MyFileSystem.FileExists(absolutePath)) { MySandboxGame.Log.WriteLine("ERROR: Missing world file in campaign: " + m_activeCampaignName); Debug.Fail("ERROR: Missing world file in campaign: " + m_activeCampaignName); return; } } } // Copy the save and load the session if (string.IsNullOrEmpty(campaignDirectoryName)) { campaignDirectoryName = ActiveCampaignName + " " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); } var directory = new DirectoryInfo(Path.GetDirectoryName(absolutePath)); var targetDirectory = Path.Combine(MyFileSystem.SavesPath, campaignDirectoryName, directory.Name); while (MyFileSystem.DirectoryExists(targetDirectory)) { // Finid new unique name for the folder targetDirectory = Path.Combine(MyFileSystem.SavesPath, directory.Name + " " + MyUtils.GetRandomInt(int.MaxValue).ToString("########")); } if (File.Exists(absolutePath)) { // It is a local mod or vanilla file MyUtils.CopyDirectory(directory.FullName, targetDirectory); } else { // Its is a workshop mod var tmpPath = Path.Combine(Path.GetTempPath(), "TMP_CAMPAIGN_MOD_FOLDER"); var worldFolderAbsolutePath = Path.Combine(tmpPath, Path.GetDirectoryName(relativePath)); // Extract the mod to temp, copy the world folder to target directory, remove the temp folder MyZipArchive.ExtractToDirectory(m_activeCampaign.ModFolderPath, tmpPath); MyUtils.CopyDirectory(worldFolderAbsolutePath, targetDirectory); Directory.Delete(tmpPath, true); } // >> LOCALIZATION // Set localization for loaded level in the after load event if (string.IsNullOrEmpty(m_selectedLanguage)) { m_selectedLanguage = m_activeCampaign.DefaultLocalizationLanguage; if (string.IsNullOrEmpty(m_selectedLanguage) && m_activeCampaign.LocalizationLanguages.Count > 0) { m_selectedLanguage = m_activeCampaign.LocalizationLanguages[0]; } } if (!string.IsNullOrEmpty(m_selectedLanguage)) { // Initilize the sessionComponent in after load event afterLoad += () => { var comp = MySession.Static.GetComponent <MyLocalizationSessionComponent>(); comp.LoadCampaignLocalization(m_activeCampaign.LocalizationPaths, m_activeCampaign.ModFolderPath); comp.SwitchLanguage(m_selectedLanguage); }; } // ATM only single player campaigns are supported if (!m_activeCampaign.IsMultiplayer) { afterLoad += () => MySession.Static.Save(); MySessionLoader.LoadSingleplayerSession(targetDirectory, afterLoad); } }