Here are the examples of the csharp api System.IO.Compression.ZipArchive.GetEntry(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
81 Examples
19
Source : SlideFile.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
public void ExtractImages(string folder)
{
Directory.CreateDirectory(folder);
using (var zip = ZipFile.OpenRead(FilePath))
{
foreach (var slide in _config.Slides)
{
if (slide.ArchiveEntryName != null)
{
var entry = zip.GetEntry(slide.ArchiveEntryName);
entry?.ExtractToFile(Path.Combine(folder, slide.ArchiveEntryName), overwrite: true);
}
}
}
}
19
Source : SlideFile.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private SlidesConfig Load()
{
using (var zip = ZipFile.OpenRead(FilePath))
{
var configEntry = zip.GetEntry(ConfigEntryName);
if (configEntry == null)
{
throw new Exception($"Could not find {ConfigEntryName} entry");
}
using (var stream = configEntry.Open())
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
var config = serializer.Deserialize<SlidesConfig>(jsonTextReader);
if (config == null)
{
throw new Exception($"Could not read {ConfigEntryName} entry");
}
return config;
}
}
}
}
19
Source : SlideFile.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private static BitmapImage ReadBackgroundImage(ZipArchive zip, string entryName)
{
var entry = zip.GetEntry(entryName);
if (entry == null)
{
throw new Exception($"Could not read {entryName} entry");
}
using (var stream = entry.Open())
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
BitmapImage bmp;
try
{
bmp = CreateBitmapImage(memoryStream, ignoreColorProfile: false);
}
catch (ArgumentException)
{
// probably colour profile corruption
bmp = CreateBitmapImage(memoryStream, ignoreColorProfile: true);
}
return bmp;
}
}
19
Source : ThemeFile.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private static ThemeCacheEntry ReadInternal(string themePath)
{
try
{
using (var zip = ZipFile.OpenRead(themePath))
{
var entry = zip.GetEntry(ThemeEntryName);
if (entry != null)
{
using (var stream = entry.Open())
{
var serializer = new JsonSerializer();
using (var sr = new StreamReader(stream))
using (var jsonTextReader = new JsonTextReader(sr))
{
var theme = serializer.Deserialize<OnlyVTheme>(jsonTextReader);
if (theme != null)
{
return new ThemeCacheEntry
{
ThemePath = themePath,
Theme = theme,
BackgroundImage = ReadBackgroundImage(zip)
};
}
}
}
}
}
}
catch (Exception ex)
{
Log.Logger.Error(ex, "Could not read theme file");
}
return null;
}
19
Source : EpubAsArchive.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private XDoreplacedent GetXmlFile(string entryPath, bool canCache = false)
{
XDoreplacedent result = null;
if (canCache)
{
result = XDocCache.Get(_epubPath, _epubCreationStampUtc, entryPath);
if (result != null)
{
return result;
}
}
ZipArchiveEntry entry = _zip.Value.GetEntry(entryPath);
if (entry != null)
{
using (var stream = entry.Open())
using (var sr = new StreamReader(stream))
{
var txt = sr.ReadToEnd();
result = XDoreplacedent.Parse(RemoveExtraneousMarkup(txt));
}
}
if (canCache)
{
XDocCache.Add(_epubPath, _epubCreationStampUtc, entryPath, result);
}
return result;
}
19
Source : PathfinderUpdaterPlugin.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
public override bool Load()
{
Config = base.Config;
IsEnabled = Config.Bind<bool>("AutoUpdater", "EnableAutoUpdates", true, "Enables or disables automatic updates for PathfinderAPI");
EnablePreReleases = Config.Bind<bool>("AutoUpdater", "UsePreReleases", false, "Whether or not to automatically update to beta versions");
AcceptedUpdate = Config.Bind<string>("AutoUpdater", "LatestAcceptedUpdate", "", "Used internally to keep track of whether you accepted the update or not");
CurrentVersion = Config.Bind<string>("AutoUpdater", "CurrentVersion", HacknetChainloader.VERSION,
"Used internally to keep track of version.\nIf you want to skip updating to a version but keep the updater on, set this manually to the latest verison.");
HarmonyInstance.PatchAll(typeof(PathfinderUpdaterPlugin));
if (Type.GetType("Mono.Runtime") != null)
{
HarmonyInstance.Patch(
AccessTools.Method(
typeof(ConfigurationManager), "OpenExeConfigurationInternal"),
prefix: new HarmonyMethod(AccessTools.Method(typeof(PathfinderUpdaterPlugin), nameof(FixConfig))));
}
if (!IsEnabled.Value)
return true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("a", "1"));
JArray releases;
try
{
releases = JArray.Parse(client
.GetAsync("https://api.github.com/repos/Arkhist/Hacknet-Pathfinder/releases").Result.Content
.ReadreplacedtringAsync().Result);
}
catch (Exception e)
{
Log.Log(LogLevel.Error, e);
client.Dispose();
return true;
}
Version tag = null;
JToken release = null;
foreach (var possibleRelease in releases)
{
var possibleTag = Version.Parse(possibleRelease.Value<string>("tag_name").Substring(1));
if (possibleTag.PreRelease != null && !EnablePreReleases.Value)
continue;
tag = possibleTag;
release = possibleRelease;
break;
}
if (HacknetChainloader.Version.Major != tag.Major)
{
Log.LogWarning($"Latest version of Pathfinder is major {tag.Major}, which is higher than Chainloader version {HacknetChainloader.Version.Major}. Please update manually!");
}
if (Version.Parse(CurrentVersion.Value).Equals(tag))
return true;
if (tag.ToString() != AcceptedUpdate.Value)
{
VersionToRequest = tag;
return true;
}
var archive = new ZipArchive(client.GetAsync(release["replacedets"].First(x => x.Value<string>("name") == "Pathfinder.Release.zip").Value<string>("browser_download_url")).Result.Content.ReadreplacedtreamAsync().Result);
var pfapiPath = Directory.GetFiles(Paths.PluginPath, "PathfinderAPI.dll", SearchOption.AllDirectories)[0];
File.Delete(pfapiPath);
var file = File.OpenWrite(pfapiPath);
archive.GetEntry("BepInEx/plugins/PathfinderAPI.dll").Open().CopyTo(file);
file.Flush();
file.Dispose();
archive.Dispose();
client.Dispose();
return true;
}
19
Source : Program.cs
with GNU General Public License v3.0
from beralves
with GNU General Public License v3.0
from beralves
static void Main(string[] args)
{
string[] requiredArgs = { "--token", "--organization", "--outdir" };
if (args.Intersect(requiredArgs).Count() == 3)
{
const string version = "api-version=5.1-preview.1";
string auth = "Basic " + Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", args[Array.IndexOf(args, "--token") + 1])));
string baseURL = "https://dev.azure.com/" + args[Array.IndexOf(args, "--organization") + 1] + "/";
string outDir = args[Array.IndexOf(args, "--outdir") + 1] + "\\";
var clientProjects = new RestClient(baseURL + "_apis/projects?" + version);
var requestProjects = new RestRequest(Method.GET);
requestProjects.AddHeader("Authorization", auth);
IRestResponse responseProjects = clientProjects.Execute(requestProjects);
Projects projects = JsonConvert.DeserializeObject<Projects>(responseProjects.Content);
foreach (Project project in projects.value)
{
Console.WriteLine(project.name);
var clientRepos = new RestClient(baseURL + project.name + "/_apis/git/repositories?" + version);
var requestRepos = new RestRequest(Method.GET);
requestRepos.AddHeader("Authorization", auth);
IRestResponse responseRepos = clientRepos.Execute(requestRepos);
Repos repos = JsonConvert.DeserializeObject<Repos>(responseRepos.Content);
foreach (Repo repo in repos.value)
{
Console.Write("\n\t" + repo.name);
var clienreplacedems = new RestClient(baseURL + "_apis/git/repositories/" + repo.id + "/items?recursionlevel=full&" + version);
var requesreplacedems = new RestRequest(Method.GET);
requesreplacedems.AddHeader("Authorization", auth);
IRestResponse responseItems = clienreplacedems.Execute(requesreplacedems);
Items items = JsonConvert.DeserializeObject<Items>(responseItems.Content);
Console.Write(" - " + items.count + "\n");
if (items.count > 0)
{
var clientBlob = new RestClient(baseURL + "_apis/git/repositories/" + repo.id + "/blobs?" + version);
var requestBlob = new RestRequest(Method.POST);
requestBlob.AddJsonBody(items.value.Where(itm => itm.gitObjectType == "blob").Select(itm => itm.objectId).ToList());
requestBlob.AddHeader("Authorization", auth);
requestBlob.AddHeader("Accept", "application/zip");
clientBlob.DownloadData(requestBlob).SaveAs(outDir + project.name + "_" + repo.name + "_blob.zip");
File.WriteAllText(outDir + project.name + "_" + repo.name + "_tree.json", responseItems.Content);
if (Array.Exists(args, argument => argument == "--unzip"))
{
if (Directory.Exists(outDir + project.name + "_" + repo.name)) Directory.Delete(outDir + project.name + "_" + repo.name, true);
Directory.CreateDirectory(outDir + project.name + "_" + repo.name);
ZipArchive archive = ZipFile.OpenRead(outDir + project.name + "_" + repo.name + "_blob.zip");
foreach (Item item in items.value)
if (item.isFolder) Directory.CreateDirectory(outDir + project.name + "_" + repo.name + item.path);
else archive.GetEntry(item.objectId).ExtractToFile(outDir + project.name + "_" + repo.name + item.path, true);
}
}
}
}
}
}
19
Source : Session.cs
with GNU General Public License v3.0
from BigETI
with GNU General Public License v3.0
from BigETI
public static Session Load(string path)
{
Session ret = null;
try
{
if (path != null)
{
if (File.Exists(path))
{
using (ZipArchive archive = ZipFile.Open(path, ZipArchiveMode.Read))
{
ZipArchiveEntry entry = archive.GetEntry("meta.json");
if (entry != null)
{
using (Stream stream = entry.Open())
{
SessionDataContract session_data = serializer.ReadObject(stream) as SessionDataContract;
if (session_data != null)
{
ret = new Session(path, session_data);
}
}
}
}
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
return ret;
}
19
Source : SessionUserControl.cs
with GNU General Public License v3.0
from BigETI
with GNU General Public License v3.0
from BigETI
private void ViewSelectedImage()
{
Dictionary<string, Process> processes = new Dictionary<string, Process>();
try
{
string temp_path = Path.Combine(Path.GetTempPath(), "SAMPLauncherNET");
if (!(Directory.Exists(temp_path)))
{
Directory.CreateDirectory(temp_path);
}
using (ZipArchive archive = ZipFile.Open(session.Path, ZipArchiveMode.Read))
{
uint id = 0U;
foreach (ListViewItem item in galleryListView.SelectedItems)
{
try
{
string path = (string)(item.Tag);
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry != null)
{
string destination_path;
do
{
destination_path = Path.Combine(temp_path, "session_" + id + ".png");
++id;
}
while (File.Exists(destination_path));
using (FileStream file_stream = File.Open(destination_path, FileMode.Create))
{
using (Stream stream = entry.Open())
{
stream.CopyTo(file_stream);
}
}
Process process = Process.Start(destination_path);
if (process != null)
{
processes.Add(destination_path, process);
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
MessageBox.Show(e.Message, Utils.Translator.GetTranslation("ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
foreach (KeyValuePair<string, Process> process in processes)
{
try
{
process.Value.WaitForExit();
if (File.Exists(process.Key))
{
File.Delete(process.Key);
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
19
Source : SessionUserControl.cs
with GNU General Public License v3.0
from BigETI
with GNU General Public License v3.0
from BigETI
private void gallerySavePictureBox_Click(object sender, EventArgs e)
{
saveFileDialog.Filter = "Portable Network Graphics (*.png)|*.png|All files (*.*)|*.*";
try
{
using (ZipArchive archive = ZipFile.Open(session.Path, ZipArchiveMode.Read))
{
foreach (ListViewItem item in galleryListView.SelectedItems)
{
try
{
string path = (string)(item.Tag);
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry != null)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string destination_path = saveFileDialog.FileName;
if (File.Exists(destination_path))
{
File.Delete(destination_path);
}
using (FileStream file_stream = File.Open(destination_path, FileMode.Create))
{
using (Stream stream = entry.Open())
{
stream.CopyTo(file_stream);
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
MessageBox.Show(ex.Message, Utils.Translator.GetTranslation("ERROR"), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
19
Source : SessionUserControl.cs
with GNU General Public License v3.0
from BigETI
with GNU General Public License v3.0
from BigETI
private void DeleteSelectedImage()
{
List<string> paths = new List<string>();
foreach (ListViewItem item in galleryListView.SelectedItems)
{
string path = (string)(item.Tag);
if (File.Exists(path))
{
paths.Add(path);
}
}
if (paths.Count > 0)
{
if (MessageBox.Show(Utils.Translator.GetTranslation("DELETE_SELECTED_IMAGES"), Utils.Translator.GetTranslation("DELETE_SELECTED_IMAGES_replacedLE"), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
{
using (ZipArchive archive = ZipFile.Open(session.Path, ZipArchiveMode.Update))
{
foreach (string path in paths)
{
try
{
ZipArchiveEntry entry = archive.GetEntry(path);
if (entry != null)
{
entry.Delete();
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
}
}
}
ReloadGallery();
}
}
}
19
Source : ApkHelper.cs
with Apache License 2.0
from dotMorten
with Apache License 2.0
from dotMorten
public static void GetAPKInfo(string path, out string apk_id, out string activity)
{
apk_id = "";
activity = "";
using (MemoryStream ms = new MemoryStream())
{
using (var file = System.IO.Compression.ZipFile.OpenRead(path))
{
var entry = file.GetEntry("AndroidManifest.xml");
if (entry != null)
{
using (var manifestStream = entry.Open())
{
manifestStream.CopyTo(ms);
ms.Seek(0, SeekOrigin.Begin);
}
}
}
var reader = new AndroidXmlReader(ms);
while (reader.Read())
{
if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "manifest")
{
if (reader.MoveToAttribute("package"))
{
apk_id = reader.Value;
}
}
else if(reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "activity")
{
if (reader.MoveToAttribute("name", "http://schemas.android.com/apk/res/android"))
{
activity = reader.Value;
}
}
}
}
}
19
Source : ModPage.xaml.cs
with MIT License
from Goose-Bomb
with MIT License
from Goose-Bomb
private void LoadModInfo(string path)
{
ModInfo mod = new ModInfo()
{
FileName = Path.GetFileNameWithoutExtension(path),
IsEnabled = path.EndsWith(".disabled") ? false : true
};
using (var archive = ZipFile.OpenRead(path))
{
var entry = archive.GetEntry("mcmod.info");
if (entry != null)
{
string json = new StreamReader(entry.Open(), System.Text.Encoding.UTF8).ReadToEnd();
try
{
JsonData ModInfo = JsonMapper.ToObject(json.Substring(1, json.Length - 1));
mod.Name = ModInfo["name"]?.ToString();
mod.Description = ModInfo["description"]?.ToString();
mod.Url = ModInfo["url"]?.ToString();
}
catch
{
};
}
}
if (path.EndsWith(".zip")) FileSystem.RenameFile(path, mod.Name + ".jar");
if (mod.Name == null) mod.Name = mod.FileName;
Dispatcher.BeginInvoke((Action)delegate ()
{
_currentMods.Add(mod);
});
}
19
Source : ResourcepackPage.xaml.cs
with MIT License
from Goose-Bomb
with MIT License
from Goose-Bomb
private ResPack GetResPackFromDisk(string path)
{
ResPack pack = new ResPack()
{
Name = Path.GetFileName(path),
};
if (path.EndsWith(".zip"))
{
using (var archive = ZipFile.OpenRead(path))
{
using (var sr = new StreamReader(archive.GetEntry("pack.mcmeta").Open(), Encoding.UTF8))
{
GetPackInfo(sr.ReadToEnd(), ref pack);
}
using (var stream = archive.GetEntry("pack.png").Open())
{
var ms = new MemoryStream();
stream.CopyTo(ms);
GetPackCover(ms, ref pack);
ms.Dispose();
}
archive.Dispose();
}
}
else
{
if (File.Exists(path + @"/pack.mcmeta"))
{
GetPackInfo(File.ReadAllText(path + @"/pack.mcmeta", Encoding.UTF8), ref pack);
}
if (File.Exists(path + @"/pack.png"))
{
var fs = File.Open(path + @"/pack.png", FileMode.Open);
GetPackCover(fs, ref pack);
fs.Dispose();
}
}
return pack;
void GetPackCover(Stream stream, ref ResPack _pack)
{
_pack.Cover = new BitmapImage();
_pack.Cover.BeginInit();
_pack.Cover.StreamSource = stream;
_pack.Cover.DecodePixelWidth = 64;
_pack.Cover.DecodePixelHeight = 64;
_pack.Cover.CacheOption = BitmapCacheOption.OnLoad;
_pack.Cover.EndInit();
_pack.Cover.Freeze();
}
void GetPackInfo(string str, ref ResPack _pack)
{
var PackInfo = JsonMapper.ToObject(str)[0];
_pack.Format = (int)PackInfo["pack_format"];
string mcVersion = "适用版本:";
switch(_pack.Format)
{
case 1: mcVersion += "1.8及以下\n"; break;
case 2: mcVersion += "1.9-1.10\n"; break;
case 3: mcVersion += "1.11-1.12\n"; break;
case 4: mcVersion += "1.13"; break;
default: break;
}
_pack.Description = mcVersion + PackInfo["description"].ToString();
}
}
19
Source : ForgeInstall.xaml.cs
with MIT License
from Goose-Bomb
with MIT License
from Goose-Bomb
private async void InstallForgeAsync(object sender, RoutedEventArgs e)
{
if (_forgeList.SelectedIndex == -1)
{
MessageBox.Show("请选择要安装的Forge版本!", "(。•ˇ‸ˇ•。)", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
_downloadButton.IsEnabled = false;
var core = App.Core;
var forge = VersionForges[_forgeList.SelectedIndex];
var forgeName = $"{_mcVersion}-{forge.Version}";
var newVersionID = $"{_mcVersion}-forge{forgeName}";
foreach(var version in Config.Args.Versions)
{
if(version.ID == newVersionID)
{
MessageBox.Show($"{forgeName} 版本的forge已经安装!", "┑( ̄Д  ̄)┍");
return;
}
}
var newVersionPath = $"{core.GameRootPath}\\versions\\{newVersionID}";
var forgeJarPath = $"{core.GameRootPath}\\libraries\\net\\minecraftforge\\forge\\{forgeName}\\forge-{forgeName}.jar";
var downloadName = forgeName + ((forge.Branch == null) ? null : $"-{forge.Branch}");
var forgeDownload = new List<DownloadInfo>()
{
new DownloadInfo
{
Path = forgeJarPath,
Url = $"{DownloadHelper.BaseUrl.ForgeBaseUrl}{downloadName}/forge-{downloadName}-universal.jar",
}
};
var downloadPage = new Pages.DownloadPage();
(Application.Current.MainWindow as MainWindow).Frame.Navigate(downloadPage);
bool hasDownloadSucceeded = await downloadPage.StartDownloadAsync(forgeDownload, "下载Forge");
if (!hasDownloadSucceeded)
{
MessageBox.Show($"下载 {_mcVersion} 版本Forge失败");
_downloadButton.IsEnabled = true;
return;
}
try
{
if (!Directory.Exists(newVersionPath))
{
Directory.CreateDirectory(newVersionPath);
}
JsonData jsonData;
string jsonText;
using (var archive = ZipFile.OpenRead(forgeJarPath))
{
var entry = archive.GetEntry("version.json");
using (var sr = new StreamReader(entry.Open(), System.Text.Encoding.UTF8))
{
jsonData = JsonMapper.ToObject(sr.ReadToEnd());
}
}
jsonData["id"] = newVersionID;
jsonText = jsonData.ToJson();
if (!jsonData.ContainsKey("inheritsFrom"))
{
jsonText = jsonText.Substring(0, jsonText.Length - 1) + $",\"inheritsFrom\": \"{_mcVersion}\"}}";
}
File.WriteAllText($"{newVersionPath}\\{newVersionID}.json", jsonText, System.Text.Encoding.UTF8);
}
catch(Exception ex)
{
MessageBox.Show($"安装 {_mcVersion} 版本Forge失败\n{ex.Message}");
_downloadButton.IsEnabled = true;
return;
}
var newVersion = core.GetVersion(newVersionID);
Config.Args.Versions.Add(newVersion);
Config.Args.VersionIndex = Config.Args.Versions.IndexOf(newVersion);
MessageBox.Show($"安装{_mcVersion}版本Forge成功");
_downloadButton.IsEnabled = true;
}
19
Source : ResourcepackPage.xaml.cs
with MIT License
from Goose-Bomb
with MIT License
from Goose-Bomb
private void AddNewMods(object sender, RoutedEventArgs e)
{
var dialog = new Microsoft.Win32.OpenFileDialog()
{
Multiselect = true,
replacedle = "请选择资源包",
Filter = "Minrcraft资源包|*.zip",
};
if (dialog.ShowDialog() ?? false)
{
foreach (var path in dialog.FileNames)
{
using (var archive = ZipFile.OpenRead(path))
{
if (archive.GetEntry("pack.mcmeta") == null)
{
MessageBox.Show(path + "\n不是有效的资源包文件", "你可能选了假资源包", MessageBoxButton.OK, MessageBoxImage.Information);
continue;
}
}
var CopyTo = PacksDir + Path.GetFileName(path);
if (!File.Exists(CopyTo))
{
var pack = GetResPackFromDisk(path);
pack.IsEnabled = false;
File.Copy(path, CopyTo);
Dispatcher.BeginInvoke((Action)delegate ()
{
Disabled_Pack.Add(pack);
});
}
}
}
}
19
Source : ModPage.xaml.cs
with MIT License
from Goose-Bomb
with MIT License
from Goose-Bomb
private void CopyMods(string[] filePaths)
{
Task.Run(() =>
{
foreach (string path in filePaths.Where(p => p.EndsWith(".jar") || p.EndsWith(".zip")))
{
using (var archive = ZipFile.OpenRead(path))
{
if (archive.GetEntry("META-INF/") == null)
{
MessageBox.Show(path + "\n不是有效的mod文件", "你可能选了假mod", MessageBoxButton.OK, MessageBoxImage.Information);
continue;
}
}
string CopyTo = _modsDir + Path.GetFileNameWithoutExtension(path) + ".jar";
if (!File.Exists(CopyTo))
{
LoadModInfo(path);
File.Copy(path, CopyTo, true);
}
}
});
}
19
Source : Mod.cs
with GNU General Public License v3.0
from HeicoDev
with GNU General Public License v3.0
from HeicoDev
public static async Task<bool> Extract(OpenFileDialog ofd)
{
try
{
await MediaStream.Dispose();
using (var fileStream = new FileStream(ofd.FileName, FileMode.Open))
{
using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Read))
{
var entry = await Task.Run(() => zipArchive.GetEntry("ModInfo.ini"));
if (entry != null)
{
string tempFile = Path.GetTempFileName();
await Task.Run(() => entry.ExtractToFile(tempFile, true));
var iniFile = new IniFile(tempFile);
string name = iniFile.Read("Name", "ModInfo"),
path = Dirs.Projects + @"\" + name;
if (Directory.Exists(path))
{
var result = MessageBox.Show("A mod with the same name exists already.\nThe old mod must be overwritten to continue.\nDo you want to continue?", "Overwrite existing mod?", MessageBoxButton.YesNo);
if (result == MessageBoxResult.Yes)
{
await Task.Run(() => Directory.Delete(path, true));
await Task.Run(() => zipArchive.ExtractToDirectory(path));
}
else
{
if (File.Exists(tempFile))
await Task.Run(() => File.Delete(tempFile));
Log.Write("Extraction aborted.");
return true;
}
}
else
{
if (Directory.Exists(path))
await Task.Run(() => Directory.Delete(path, true));
await Task.Run(() => zipArchive.ExtractToDirectory(path));
}
if (File.Exists(tempFile))
await Task.Run(() => File.Delete(tempFile));
await Tree.Populate(UIElements.TreeViewModExplorer, path);
Dirs.FilesPathMod = path;
Dirs.ModName = name;
Globals.IsModAvailable = true;
}
}
}
return false;
}
catch (Exception ex)
{
Log.Error(ex.ToString());
Log.Write("Unable to extract mod project! See error.log", "error");
return true;
}
}
19
Source : ExtensionInstaller.cs
with MIT License
from JosefNemec
with MIT License
from JosefNemec
private static T GetPackedManifest<T>(string packagePath, string nanifestFileName) where T : clreplaced
{
using (var zip = ZipFile.OpenRead(packagePath))
{
var manifest = zip.GetEntry(nanifestFileName);
if (manifest == null)
{
return null;
}
using (var logStream = manifest.Open())
{
using (TextReader tr = new StreamReader(logStream))
{
return Serialization.FromYaml<T>(tr.ReadToEnd());
}
}
}
}
19
Source : ExtensionInstaller.cs
with MIT License
from JosefNemec
with MIT License
from JosefNemec
public static void VerifyExtensionPackage(string packagePath)
{
using (var zip = ZipFile.OpenRead(packagePath))
{
var manifestEntry = zip.GetEntry(PlaynitePaths.ExtensionManifestFileName);
if (manifestEntry == null)
{
logger.Error("Extension package is invalid, no manifest found.");
throw new LocalizedException(LOC.GeneralExtensionPackageError);
}
using (var logStream = manifestEntry.Open())
{
using (TextReader tr = new StreamReader(logStream))
{
var manifest = Serialization.FromYaml<ExtensionManifest>(tr.ReadToEnd());
if (manifest.Id.IsNullOrEmpty())
{
logger.Error("Extension package is invalid, no extension ID found.");
throw new LocalizedException(LOC.GeneralExtensionPackageError);
}
if (!Version.TryParse(manifest.Version, out var _))
{
logger.Error($"Extension package is invalid, version is not in correct format {manifest.Version}.");
throw new LocalizedException(LOC.GeneralExtensionPackageError);
}
}
}
if (zip.Entries.Any(a => a.Name == "Playnite.dll" || a.Name == "Playnite.Common.dll"))
{
logger.Error($"Extension package is invalid, includes not allowed Playnite dependencies.");
throw new LocalizedException(LOC.GeneralExtensionPackageError);
}
}
}
19
Source : ExtensionInstaller.cs
with MIT License
from JosefNemec
with MIT License
from JosefNemec
public static void VerifyThemePackage(string packagePath)
{
using (var zip = ZipFile.OpenRead(packagePath))
{
var manifestEntry = zip.GetEntry(PlaynitePaths.ThemeManifestFileName);
if (manifestEntry == null)
{
logger.Error("Theme package is invalid, no manifest found.");
throw new LocalizedException(LOC.GeneralThemePackageError);
}
using (var logStream = manifestEntry.Open())
{
using (TextReader tr = new StreamReader(logStream))
{
var manifest = Serialization.FromYaml<ThemeManifest>(tr.ReadToEnd());
if (manifest.Id.IsNullOrEmpty())
{
logger.Error("Theme package is invalid, no extension ID found.");
throw new LocalizedException(LOC.GeneralThemePackageError);
}
if (!Version.TryParse(manifest.Version, out var _))
{
logger.Error($"Theme package is invalid, version is not in correct format {manifest.Version}.");
throw new LocalizedException(LOC.GeneralThemePackageError);
}
}
}
if (zip.Entries.Any(a =>
a.Name == PlaynitePaths.ThemeSlnFileName ||
a.Name == PlaynitePaths.ThemeProjFileName ||
a.Name == PlaynitePaths.AppXamlFileName))
{
logger.Error($"Theme package is invalid, includes not allowed theme project files.");
throw new LocalizedException(LOC.GeneralThemePackageError);
}
}
}
19
Source : Package.cs
with MIT License
from JTinkers
with MIT License
from JTinkers
public Dictionary<string, string> GetInfo()
{
string contents;
if (IsZipped)
{
var archive = ZipFile.OpenRead(ArchivePath);
var reader = new StreamReader(archive.GetEntry("info.json").Open());
contents = reader.ReadToEnd();
//Neccessary force-disposal and close to preven IO exceptions.
reader.Dispose();
archive.Dispose();
}
else
{
contents = File.ReadAllText($@"{ArchivePath}\info.json");
}
return JsonConvert.DeserializeObject<Dictionary<string, string>>(contents);
}
19
Source : Package.cs
with MIT License
from JTinkers
with MIT License
from JTinkers
public string ReadFileContents(string fileName)
{
string contents;
if (IsZipped)
{
var archive = ZipFile.OpenRead(ArchivePath);
var reader = new StreamReader(archive.GetEntry(fileName).Open());
contents = reader.ReadToEnd();
reader.Dispose();
archive.Dispose();
}
else
{
contents = File.ReadAllText($@"{ArchivePath}\{fileName}");
}
return contents;
}
19
Source : Package.cs
with MIT License
from JTinkers
with MIT License
from JTinkers
public void WriteFileContents(string fileName, string contents)
{
if (IsZipped)
{
var archive = ZipFile.Open(ArchivePath, ZipArchiveMode.Update);
archive.GetEntry(fileName).Delete();
archive.CreateEntry(fileName);
var writer = new StreamWriter(archive.GetEntry(fileName).Open());
writer.Write(contents);
writer.Dispose();
archive.Dispose();
}
else
{
File.WriteAllText($@"{ArchivePath}\{fileName}", contents);
}
}
19
Source : ChatManager.cs
with Apache License 2.0
from kauffman12
with Apache License 2.0
from kauffman12
private void LoadCache()
{
ChannelIndex = new Dictionary<string, Dictionary<string, byte>>();
ChannelIndexUpdated = false;
if (CurrentArchive != null && CurrentArchive.Mode != ZipArchiveMode.Create)
{
try
{
var indexEntry = CurrentArchive.GetEntry(INDEX);
if (indexEntry != null)
{
using (var reader = new StreamReader(indexEntry.Open()))
{
while (!reader.EndOfStream)
{
var temp = reader.ReadLine().Split('|');
if (temp != null && temp.Length == 2)
{
ChannelIndex[temp[0]] = new Dictionary<string, byte>();
foreach (var channel in temp[1].Split(','))
{
ChannelIndex[temp[0]][channel] = 1;
UpdateChannelCache(channel); // incase main cache is out of sync with archive
}
}
}
}
}
}
catch (IOException ex)
{
LOG.Error(ex);
}
catch (InvalidDataException ide)
{
LOG.Error(ide);
}
}
}
19
Source : ChatManager.cs
with Apache License 2.0
from kauffman12
with Apache License 2.0
from kauffman12
private ZipArchiveEntry GetEntry(string key)
{
return CurrentArchive.Mode == ZipArchiveMode.Create ? CurrentArchive.CreateEntry(key) : CurrentArchive.GetEntry(key) ?? CurrentArchive.CreateEntry(key);
}
19
Source : ChatManager.cs
with Apache License 2.0
from kauffman12
with Apache License 2.0
from kauffman12
private void AddToArchive(string year, string month, string day, ChatLine chatLine, ChatType chatType, DateUtil dateUtil)
{
string entryKey = day;
string archiveKey = year + "-" + month;
if (CurrentArchiveKey != archiveKey)
{
SaveCurrent(true);
string fileName = GetFileName(year, month);
var mode = File.Exists(fileName) ? ZipArchiveMode.Update : ZipArchiveMode.Create;
CurrentArchive = OpenArchive(fileName, mode);
CurrentArchiveKey = archiveKey;
LoadCache();
}
if (entryKey != CurrentEntryKey && CurrentArchive != null)
{
SaveCurrent(false);
CurrentEntryKey = entryKey;
CurrentList = new List<ChatLine>();
var entry = CurrentArchive.Mode != ZipArchiveMode.Create ? CurrentArchive.GetEntry(CurrentEntryKey) : null;
if (entry != null)
{
using (var reader = new StreamReader(entry.Open()))
{
List<string> temp = new List<string>();
while (reader.BaseStream.CanRead && !reader.EndOfStream)
{
temp.Insert(0, reader.ReadLine()); // reverse
}
// this is so the date precision numbers are calculated in the same order
// as the new lines being added
temp.ForEach(line =>
{
var existingLine = CreateLine(dateUtil, line);
if (existingLine != null)
{
CurrentList.Insert(0, existingLine); // reverse back
}
});
}
}
}
if (CurrentList != null)
{
int index = CurrentList.BinarySearch(chatLine, RTAComparer);
if (index < 0)
{
index = Math.Abs(index) - 1;
CurrentList.Insert(index, chatLine);
UpdateCache(entryKey, chatType);
CurrentListModified = true;
}
else if (chatLine.Line != CurrentList[index].Line)
{
CurrentList.Insert(index, chatLine);
UpdateCache(entryKey, chatType);
CurrentListModified = true;
}
}
}
19
Source : Snapshot.cs
with MIT License
from KuromeSan
with MIT License
from KuromeSan
private static List<Snapshoreplacedem> GetArchiveItems(string archiveFile)
{
TaskSchedulerSnapshot ret = null;
using (var zip = ZipFile.OpenRead(archiveFile))
{
using (var hdrStr = zip.GetEntry(hdrfile).Open())
ret = new XmlSerializer(typeof(TaskSchedulerSnapshot)).Deserialize(hdrStr) as TaskSchedulerSnapshot;
if (ret == null) return null;
for (int i = 0; i < ret.Items.Count; i++)
{
if (ret.Items[i] is TaskSnapshot t)
{
var xml = zip.GetEntry(t.Path.TrimStart('\\') + ".xml");
using (var str = new StreamReader(xml.Open(), Encoding.UTF8))
t.TaskDefinitionXml = str.ReadToEnd();
}
}
}
return ret?.Items;
}
19
Source : Main.cs
with GNU General Public License v3.0
from mrojkov
with GNU General Public License v3.0
from mrojkov
[STAThread]
public static int Main(string[] args)
{
var originalArgs = args;
#if MAC
args = args.Where(s => !s.StartsWith("-psn")).ToArray();
#endif // MAC
var cli = new CommandLineApplication();
cli.Name = "Orange";
cli.Description = "Orange Launcher";
cli.HelpOption("-h --help");
var optionConsole = cli.Option<bool>("-c --console", "Console mode.", CommandOptionType.NoValue);
var optionJustBuild = cli.Option<bool>("-j --justbuild", "Build project without running executable.", CommandOptionType.NoValue);
var optionBuildProjectPath = cli.Option<string>("-b --build <PROJECT_PATH>", "Project path, default: \"Orange/Orange.%Platform%.sln\".", CommandOptionType.SingleValue);
var optionExecutablePath = cli.Option<string>("-r --run <EXECUTABLE_PATH>", "Executable path, default: \"Orange/bin/%Platform%/Release/%PlatformExecutable%\".", CommandOptionType.SingleValue);
var optionRunArgs = cli.Option<string>("-a --runargs <ARGUMENTS>", "Args to preplaced to executable.", CommandOptionType.SingleValue);
cli.Command("release", (releaseCommand) => {
releaseCommand.HelpOption("-h --help");
releaseCommand.Description = "Release provided Citrus bundle on github.";
var githubUserOption = releaseCommand.Option<string>("-u --user <GITHUB_USER_NAME>", "github user name", CommandOptionType.SingleValue);
githubUserOption.IsRequired();
var githubPreplacedwordOption = releaseCommand.Option<string>("-p --preplacedword <GITHUB_PreplacedWORD>", "github preplacedword", CommandOptionType.SingleValue);
githubPreplacedwordOption.IsRequired();
var winBundlePath = releaseCommand.Option<string>("-w --win-bundle <WINDOWS_BUNDLE_PATH>", "Path to windows bundle of Citrus.", CommandOptionType.SingleValue);
winBundlePath.IsRequired();
var macBundlePath = releaseCommand.Option<string>("-m --mac-bundle <MAC_BUNDLE_PATH>", "Path to MAC OS bundle of Citrus.", CommandOptionType.SingleValue);
macBundlePath.IsRequired();
var buildNumberOption = releaseCommand.Option<string>("-n --build-number <BUILD_NUMBER>", "Build number.", CommandOptionType.SingleValue);
buildNumberOption.IsRequired();
releaseCommand.OnExecute(async () => {
#if MAC
NSApplication.Init();
#endif // MAC
Console.WriteLine($"Build version: {buildNumberOption.ParsedValue}");
CitrusVersion citrusVersion = null;
var citrusDirectory = Toolbox.CalcCitrusDirectory();
var bundlePath = winBundlePath.ParsedValue;
using (var zipFile = ZipFile.Open(Path.Combine(citrusDirectory, bundlePath), ZipArchiveMode.Read)) {
var citrusVersionEntry = zipFile.GetEntry(CitrusVersion.Filename);
using (var stream = citrusVersionEntry.Open()) {
citrusVersion = CitrusVersion.Load(stream);
}
}
citrusVersion.BuildNumber = buildNumberOption.ParsedValue;
var client = new GitHubClient(new ProductHeaderValue(githubUserOption.ParsedValue));
client.SetRequestTimeout(TimeSpan.FromMinutes(10));
var basicAuth = new Credentials(githubUserOption.ParsedValue, githubPreplacedwordOption.ParsedValue);
client.Credentials = basicAuth;
var tagName = $"gh_{citrusVersion.Version}_{citrusVersion.BuildNumber}";
var release = new NewRelease(tagName) {
Name = "Automated release",
Body = "Automated release",
Draft = false,
Prerelease = false,
};
var result = await client.Repository.Release.Create("mrojkov", "Citrus", release);
Console.WriteLine("Created release id {0}", result.Id);
// TODO: abort upload if nothing changed
//var releases = await client.Repository.Release.GetAll("mrojkov", "Citrus");
var latest = result;
var archiveContents = File.OpenRead(Path.Combine(citrusDirectory, winBundlePath.ParsedValue));
var replacedetUpload = new ReleasereplacedetUpload() {
FileName = $"citrus_win_{tagName}.zip",
ContentType = "application/zip",
RawData = archiveContents,
Timeout = TimeSpan.FromMinutes(10),
};
var replacedet = await client.Repository.Release.Uploadreplacedet(latest, replacedetUpload);
archiveContents = File.OpenRead(Path.Combine(citrusDirectory, macBundlePath.ParsedValue));
replacedetUpload = new ReleasereplacedetUpload() {
FileName = $"citrus_mac_{tagName}.zip",
ContentType = "application/zip",
RawData = archiveContents,
Timeout = TimeSpan.FromMinutes(10),
};
replacedet = await client.Repository.Release.Uploadreplacedet(latest, replacedetUpload);
Console.WriteLine("Done uploading replacedet");
});
});
cli.Command("bundle", (bundleCommand) => {
bundleCommand.HelpOption("-h --help");
bundleCommand.Description = "Build Tangerine, Orange and bundle them together into zip.";
var tempOption = bundleCommand.Option<string>("-t --temp-directory <DIRECTORY_PATH>", "Temporary directory. If specified path is not full it becomes relative to Citrus directory.", CommandOptionType.SingleValue);
var outputOption = bundleCommand.Option<string>("-o --output <OUTPUT_PATH>", "Output path including bundle name (e.g. bundle_win.zip). If specified path is not full it becomes relative to Citrus directory.", CommandOptionType.SingleValue);
var buildNumberOption = bundleCommand.Option<string>("-n --build-number <BUILD_NUMBER>", "Build number.", CommandOptionType.SingleValue);
buildNumberOption.IsRequired();
bundleCommand.OnExecute(() => {
#if MAC
NSApplication.Init();
#endif // MAC
var platformSuffix =
#if WIN
"win";
#elif MAC
"mac";
#endif // WIN
orangeBuilder = new Builder(citrusDirectory) {
NeedRunExecutable = false,
SolutionPath = OrangeSolutionPath,
ExecutablePath = OrangeExecutablePath,
};
orangeBuilder.OnBuildStatusChange += Console.WriteLine;
orangeBuilder.OnBuildFail += () => Environment.Exit(1);
orangeBuilder.Start().Wait();
var tangerineBuilder = new Builder(citrusDirectory) {
#if WIN
SolutionPath = Path.Combine(citrusDirectory, "Tangerine", "Tangerine.Win.sln"),
#elif MAC
SolutionPath = Path.Combine(citrusDirectory, "Tangerine", "Tangerine.Mac.sln"),
#endif // WIN
NeedRunExecutable = false
};
tangerineBuilder.OnBuildStatusChange += Console.WriteLine;
tangerineBuilder.OnBuildFail += () => Environment.Exit(1);
tangerineBuilder.Start().Wait();
var orangeBinDir = Path.Combine(citrusDirectory, "Orange", "bin", platformSuffix, "Release");
var tangerineBinDir = Path.Combine(citrusDirectory, "Tangerine", "bin", "Release");
var orangeFiles = new FileEnumerator(orangeBinDir);
var tangerineFiles = new FileEnumerator(tangerineBinDir);
var tempPath = tempOption.HasValue() ? tempOption.ParsedValue : Path.Combine(citrusDirectory, "launcher_temp");
var outputPath = outputOption.HasValue()
? Path.Combine(citrusDirectory, outputOption.ParsedValue)
: Path.Combine(citrusDirectory, "launcher_output", $"bundle_{platformSuffix}.zip");
var outputDirectory = Path.GetDirectoryName(outputPath);
if (Directory.Exists(tempPath)) {
Directory.Delete(tempPath, true);
}
if (Directory.Exists(outputDirectory)) {
Directory.Delete(outputDirectory, true);
}
Directory.CreateDirectory(tempPath);
Directory.CreateDirectory(outputDirectory);
Console.WriteLine($"Temporary Directory is {tempPath}");
Console.WriteLine($"Output Path is {outputPath}");
Console.WriteLine("Begin copying artifacts to temporary directory");
#if WIN
foreach (var fi in orangeFiles.Enumerate()) {
var srcPath = Path.Combine(orangeBinDir, fi.Path);
var dstPath = Path.Combine(tempPath, fi.Path);
Directory.CreateDirectory(Path.GetDirectoryName(dstPath));
File.Copy(srcPath, dstPath);
Console.WriteLine($"Copying {srcPath} => {dstPath}");
}
foreach (var fi in tangerineFiles.Enumerate()) {
var srcPath = Path.Combine(tangerineBinDir, fi.Path);
var dstPath = Path.Combine(tempPath, fi.Path);
Directory.CreateDirectory(Path.GetDirectoryName(dstPath));
File.Copy(srcPath, dstPath, true);
Console.WriteLine($"Copying {srcPath} => {dstPath}");
}
#elif MAC
var orangeGuiAppPath = Path.Combine(orangeBinDir, "Orange.GUI.app");
var tangerineAppPath = Path.Combine(tangerineBinDir, "Tangerine.app");
var process = new System.Diagnostics.Process {
StartInfo = {
FileName = "cp",
Arguments = $"-R {orangeGuiAppPath} {tempPath}"
}
};
process.Start();
process.WaitForExit();
process = new System.Diagnostics.Process {
StartInfo = {
FileName = "cp",
Arguments = $"-R {tangerineAppPath} {tempPath}"
}
};
process.Start();
process.WaitForExit();
#endif // WIN
CitrusVersion citrusVersion = null;
using (var stream = File.Open(Path.Combine(citrusDirectory, Orange.CitrusVersion.Filename), FileMode.Open)) {
citrusVersion = CitrusVersion.Load(stream);
citrusVersion.IsStandalone = true;
citrusVersion.BuildNumber = buildNumberOption.ParsedValue;
// TODO: fill in checksums for each file?
}
using (var stream = File.Open(Path.Combine(tempPath, Orange.CitrusVersion.Filename), FileMode.CreateNew)) {
CitrusVersion.Save(citrusVersion, stream);
}
Console.WriteLine($"Begin zipping archive.");
#if WIN
ZipFile.CreateFromDirectory(tempPath, outputPath, CompressionLevel.Optimal, false);
#elif MAC
var tarPath = Path.Combine(outputDirectory, "bundle.tar");
process = new System.Diagnostics.Process {
StartInfo = {
FileName = "tar",
Arguments = $"-cvpf {tarPath} Tangerine.app Orange.GUI.app {CitrusVersion.Filename}",
WorkingDirectory = $"{tempPath}",
}
};
process.Start();
process.WaitForExit();
using (FileStream stream = new FileStream(outputPath, FileMode.Create))
using (ZipArchive zipArchive = new ZipArchive(stream, ZipArchiveMode.Create)) {
zipArchive.CreateEntryFromFile(tarPath, "bundle.tar");
}
#endif // WIN
Console.WriteLine("Done.");
});
});
cli.OnExecute(() => {
#if WIN
var stdoutHandle = GetStdHandle(StandardHandle.Output);
if (args.Length == 0 && stdoutHandle != INVALID_HANDLE_VALUE) {
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_SHOW;
si.hStdOutput = INVALID_HANDLE_VALUE;
si.hStdInput = INVALID_HANDLE_VALUE;
si.hStdError = INVALID_HANDLE_VALUE;
CreateProcessW(IntPtr.Zero,
GetCommandLineW(),
IntPtr.Zero,
IntPtr.Zero,
true,
0x00000008, // DETACHED_PROCESS
IntPtr.Zero,
IntPtr.Zero,
ref si,
out pi
);
return 0;
}
#endif // WIN
string solutionPath = OrangeSolutionPath;
string executablePath = OrangeExecutablePath;
if (optionBuildProjectPath.HasValue()) {
solutionPath = Path.Combine(Environment.CurrentDirectory, optionBuildProjectPath.ParsedValue);
}
if (optionExecutablePath.HasValue()) {
executablePath = Path.Combine(Environment.CurrentDirectory, optionExecutablePath.ParsedValue);
}
orangeBuilder = new Builder(citrusDirectory) {
NeedRunExecutable = !optionJustBuild.HasValue(),
SolutionPath = solutionPath,
ExecutablePath = executablePath,
ExecutableArgs = optionRunArgs.ParsedValue
};
if (optionConsole.HasValue()) {
StartConsoleMode();
} else {
// OS X preplacedes `-psn_<number>` to process when start from Finder, so we cut it for
// cli parser, but preplaced original args to OS X's NSApplication.Main
StartUIMode(originalArgs);
}
return 0;
});
try {
cli.Execute(args);
} catch (CommandParsingException e) {
Console.WriteLine(e.Message);
return 1;
}
return 0;
}
19
Source : DownloadForm.cs
with GNU General Public License v3.0
from mrphil2105
with GNU General Public License v3.0
from mrphil2105
private async Task<bool> DownloadExtractAsync()
{
byte[] fileBytes = null;
try
{
fileBytes = await _downloader.DownloadAsync(_cancellationTokenSource.Token);
}
catch (WebException webException)
{
this.ShowError($"Unable to download SteamCMD: {webException.Message}", "Download Failed");
}
if (fileBytes != null)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(_server.SteamCMDPath));
using (var memoryStream = new MemoryStream(fileBytes))
using (var zipFile = new ZipArchive(memoryStream))
using (var entryStream = zipFile.GetEntry("steamcmd.exe").Open())
using (var fileStream = new FileStream(_server.SteamCMDPath, FileMode.Create, FileAccess.Write))
{
await entryStream.CopyToAsync(fileStream);
return true;
}
}
catch
{
this.ShowError("An error has occurred when extracting SteamCMD.", "Extraction Failed");
}
}
return false;
}
19
Source : ZipFileIndex.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public void Read(string zipPath, ZipFileEntryDelegate func)
{
var file = _zip.GetEntry(zipPath);
if (file == null)
return;
try
{
func(file.Open());
}
catch
{
// ignore
}
}
19
Source : ZipFileIndex.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public bool Delete(string zipPath)
{
var file = _zip.GetEntry(zipPath);
if (file == null)
return false;
try
{
file.Delete();
return true;
}
catch
{
return false;
}
}
19
Source : ZipFileIndex.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public bool Update(string zipPath, ZipFileEntryDelegate func)
{
var file = _zip.GetEntry(zipPath);
if (file == null)
return false;
try
{
file.Delete();
return Create(zipPath, func);
}
catch
{
return false;
}
}
19
Source : ZipFileIndex.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public bool Create(string zipPath, ZipFileEntryDelegate func)
{
var file = _zip.GetEntry(zipPath);
if (file != null)
return false;
try
{
var entry = _zip.CreateEntry(zipPath);
func(entry.Open());
AddEntry(entry);
return true;
}
catch
{
return false;
}
}
19
Source : LoadStrategyFileStream.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public override Stream GetEntry(string entry) => _zip.GetEntry(entry)?.Open();
19
Source : AnnotationProScraper.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
protected override IEnumerable<Dictionary<string, object>> Execute(string file)
{
AnnotationSystemDataSet model = null;
using(var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
using (var zip = new ZipArchive(fs))
model = XmlSerializerHelper.Deserialize<AnnotationSystemDataSet>(zip.GetEntry("annotation.xml").Open());
var guid = model?.Layer.Where(layer => layer.Name == "Text").Select(layer => layer.Id).FirstOrDefault();
if (guid == null)
return null;
return from segment in model.Segment
where segment.IdLayer == guid
select new Dictionary<string, object>
{
{"Text", segment.Label},
{"Duration", segment.Duration},
{"Feature", segment.Feature},
{"Group", segment.Group},
{"Id", segment.Id},
{"Language", segment.Language},
{"Markter", segment.Marker},
{"Nane", segment.Name},
{"Paramter1", segment.Parameter1},
{"Paramter2", segment.Parameter2},
{"Paramter3", segment.Parameter3}
};
}
19
Source : ExporterAnnoationPro.cs
with GNU Affero General Public License v3.0
from notesjor
with GNU Affero General Public License v3.0
from notesjor
public override void Export(IHydra hydra, string path)
{
AnnotationSystemDataSet ant = null;
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var zip = new ZipArchive(fs))
ant = XmlSerializerHelper.Deserialize<AnnotationSystemDataSet>(zip.GetEntry("annotation.xml").Open());
if (ant == null)
return;
var antLayer = new List<Layer>(ant.Layer);
antLayer.AddRange(
hydra.Layers.Where(layer => layer.Displayname != "Wort" && layer.Displayname != "Satz")
.Select(
layer =>
new Layer
{
Id = layer.Guid.ToString("D"),
IsVisible = true,
Name = layer.Displayname,
ShowOnSpectrogram = true,
BackColor = "-3281999",
ForeColor = "-16777216",
Height = "70",
ChartMinimum = "0",
ChartMaximum = "100",
FontSize = "10"
}));
ant.Layer = antLayer.ToArray();
var dic = ant.Segment.ToDictionary(segment => segment.Id);
var antSegments = new List<Segment>(ant.Segment);
antSegments.AddRange(
from doreplacedentGuid in hydra.DoreplacedentGuids
let meta = hydra.GetDoreplacedentMetadata(doreplacedentGuid)
where meta.ContainsKey("Id") && dic.ContainsKey(meta["Id"].ToString())
let segment = dic[meta["Id"].ToString()]
from layer in hydra.Layers
where layer.Displayname != "Wort" && layer.Displayname != "Satz"
select BuildSegment(segment, doreplacedentGuid, layer));
ant.Segment = antSegments.ToArray();
var dir = Path.GetDirectoryName(path);
if (dir == null)
throw new DirectoryNotFoundException();
var nFile = Path.Combine(dir, Path.GetFileNameWithoutExtension(path) + ".bak.ant");
if (!File.Exists(nFile))
File.Copy(path, nFile, false);
using (var fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
using (var zip = new ZipArchive(fs, ZipArchiveMode.Update))
XmlSerializerHelper.Serialize(ant, zip.GetEntry("annotation.xml").Open());
}
19
Source : Program.cs
with GNU General Public License v3.0
from OG-Sadpanda
with GNU General Public License v3.0
from OG-Sadpanda
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(@"
_____ _ _____ _
/ ___| | / ___| | |
\ `--.| |__ __ _ _ __ _ __ \ `--.__ _____ _ __ __| |
`--. \ '_ \ / _` | '__| '_ \ `--. \ \ /\ / / _ \| '__/ _` |
/\__/ / | | | (_| | | | |_) /\__/ /\ V V / (_) | | | (_| |
\____/|_| |_|\__,_|_| | .__/\____/ \_/\_/ \___/|_| \__,_|
| |
|_|
" +
"" +
"Developed By: @sadpanda_sec \n\n" +
"Description: Read Contents of Word Doreplacedents (Docx).\n\n" +
"Usage: SharpSword.exe C:\\Some\\Path\\To\\Doreplacedent.docx");
System.Environment.Exit(0);
}
else if (args.Length == 1)
{
if (File.Exists(args[0]) && Path.GetExtension(args[0]).ToLower() == ".docx")
{
var docPath = Path.GetFullPath(args[0]);
using (var archive = ZipFile.OpenRead(docPath))
{
var xmlFile = archive.GetEntry(@"word/doreplacedent.xml");
if (xmlFile == null)
return;
using (var stream = xmlFile.Open())
{
using (var reader = new StreamReader(stream))
{
XmlDoreplacedent xmldoc = new XmlDoreplacedent();
xmldoc.Load(stream);
XmlNodeList plaintext = xmldoc.GetElementsByTagName("w:t");
DateTime date = DateTime.Now;
Console.WriteLine("\n" + date + ": " + "Reading Doreplacedent: " + docPath + "\n\n");
for (int i=0; i < plaintext.Count; i++)
{
Console.WriteLine(plaintext[i].InnerText);
}
System.Environment.Exit(0);
}
}
}
}
else
{
Console.WriteLine("File Does Not Exist Or File Extention is Not DOCX");
System.Environment.Exit(0);
}
}
else
{
if (args.Length > 1)
{
Console.WriteLine("Error...Provided more than one command line argument\n\n" +
"Usage: SharpSword.exe C:\\Some\\Path\\To\\Doreplacedent.docx");
System.Environment.Exit(0);
}
}
}
19
Source : Platform.cs
with GNU Affero General Public License v3.0
from OpenIIoT
with GNU Affero General Public License v3.0
from OpenIIoT
public virtual IResult<string> ExtractZipFile(string zipFile, string file, string destination, bool overwrite = true)
{
logger.EnterMethod(xLogger.Params(zipFile, file, destination, overwrite));
logger.Debug($"Extracting file '{file}' from zip file '{zipFile}' into directory '{destination}'...");
IResult<string> retVal = new Result<string>();
try
{
logger.Trace($"Opening zip file '{zipFile}'...");
using (ZipArchive archive = ZipFile.Open(zipFile, ZipArchiveMode.Read))
{
ZipArchiveEntry entry = archive.GetEntry(file);
string extractedFile = Path.Combine(destination, entry.Name);
logger.Trace($"Extracting file '{file}'...");
entry.ExtractToFile(extractedFile, overwrite);
retVal.ReturnValue = extractedFile;
}
}
catch (Exception ex)
{
logger.Exception(LogLevel.Trace, ex);
retVal.AddError(ex.Message);
retVal.AddError($"Failed to extract file '{Path.GetFileName(file)}' from zip file '{Path.GetFileName(zipFile)}'.");
}
retVal.LogResult(logger.Debug);
logger.ExitMethod(retVal.ResultCode);
return retVal;
}
19
Source : ModelData.cs
with MIT License
from patlevin
with MIT License
from patlevin
private static byte[] ReadModel(ZipArchive archive, string name)
{
var entry = archive.GetEntry(name);
if (entry == null)
{
throw new InvalidDataException(name);
}
using (var stream = entry.Open())
{
using (var output = new MemoryStream())
{
var buffer = new byte[32768];
int read = 0;
do
{
read = stream.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, read);
} while (read == buffer.Length);
return output.ToArray();
}
}
}
19
Source : ArchiveSource.cs
with MIT License
from patlevin
with MIT License
from patlevin
internal override Stream OpenFile(string name, out int sizeInBytes)
{
var entry = archive.GetEntry(name);
if (entry == null)
{
throw new FileNotFoundException(name);
}
sizeInBytes = (int)entry.Length;
return entry.Open();
}
19
Source : ArchiveSource.cs
with MIT License
from patlevin
with MIT License
from patlevin
internal override bool ContainsFile(string name)
{
return archive.GetEntry(name) != null;
}
19
Source : Theme.cs
with GNU General Public License v3.0
from percyqaz
with GNU General Public License v3.0
from percyqaz
public Stream GetFile(params string[] path)
{
string p = Path.Combine(path);
if (zipFile != null)
{
return zipFile.GetEntry(p.Replace(Path.DirectorySeparatorChar,'/')).Open();
}
p = Path.Combine(ThemePath, p);
return File.OpenRead(p);
}
19
Source : ZipArtists.xaml.cs
with MIT License
from project-violet
with MIT License
from project-violet
private async void ProcessPath(string path)
{
FileIndexor fi = new FileIndexor();
await fi.ListingDirectoryAsync(path);
string root_directory = fi.RootDirectory;
Dictionary<string, ZipArtistsArtistModel> artist_dic = new Dictionary<string, ZipArtistsArtistModel>();
foreach (var x in fi.Directories)
{
await Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
ProgressText.Text = x.Item1;
}));
Dictionary<string, HitomiJsonModel> article_data = new Dictionary<string, HitomiJsonModel>();
DateTime last_access_time = DateTime.MinValue;
DateTime craete_time = DateTime.Now;
foreach (var file in x.Item3)
{
if (!file.FullName.EndsWith(".zip")) continue;
var zipFile = ZipFile.Open(file.FullName, ZipArchiveMode.Read);
if (zipFile.GetEntry("Info.json") == null) continue;
using (var reader = new StreamReader(zipFile.GetEntry("Info.json").Open()))
{
var json_model = JsonConvert.DeserializeObject<HitomiJsonModel>(reader.ReadToEnd());
article_data.Add(Path.GetFileName(file.FullName), json_model);
}
if (file.LastWriteTime < craete_time)
craete_time = file.LastWriteTime;
if (last_access_time < file.LastWriteTime)
last_access_time = file.LastWriteTime;
}
if (article_data.Count == 0) continue;
artist_dic.Add(x.Item1.Substring(root_directory.Length), new ZipArtistsArtistModel { ArticleData = article_data, CreatedDate = craete_time.ToString(), LastAccessDate = last_access_time.ToString(), ArtistName = Path.GetFileName(Path.GetDirectoryName(x.Item1)), Size = (long)x.Item2});
}
model = new ZipArtistsModel();
model.RootDirectory = root_directory;
model.Tag = path;
model.ArtistList = artist_dic.ToArray();
var tick = DateTime.Now.Ticks;
ZipArtistsModelManager.SaveModel($"zipartists-{Path.GetFileName(root_directory)}-{tick}.json", model);
rate_filename = $"zipartists-{Path.GetFileName(root_directory)}-{tick}-rating.json";
algorithm.Build(model);
artist_list = artist_dic.ToList();
elems.Clear();
artist_list.ForEach(x => elems.Add(Tuple.Create(x, Tuple.Create(root_directory + x.Key, 0, false))));
day_before = raws = elems;
sort_data(align_column, align_row);
await Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
CollectStatusPanel.Visibility = Visibility.Collapsed;
ArticleCount.Text = $"작가 {artist_dic.Count.ToString("#,#")}명";
PageCount.Text = $"작품 {artist_list.Select(x => x.Value.ArticleData.Count).Sum().ToString("#,#")}개";
max_page = artist_dic.Count / show_elem_per_page;
initialize_page();
}));
stack_clear();
stack_push();
}
19
Source : ZipIntegrity.xaml.cs
with MIT License
from project-violet
with MIT License
from project-violet
private void process()
{
int cnt = 0;
List<string> nv = new List<string>();
var rx = new Regex(@"^\[(\d+)\]");
foreach (var path in file_list)
{
try
{
using (var zipFile = ZipFile.OpenRead(path))
{
var entries = zipFile.Entries;
if (zipFile.GetEntry("Info.json") == null)
{
append("[INFO NOT FOUND] " + path);
nv.Add(path);
}
else
{
using (var reader = new StreamReader(zipFile.GetEntry("Info.json").Open()))
{
var json_model = JsonConvert.DeserializeObject<HitomiJsonModel>(reader.ReadToEnd());
if (rx.Match(System.IO.Path.GetFileNameWithoutExtension(path)).Success)
{
if (rx.Match(System.IO.Path.GetFileNameWithoutExtension(path)).Groups[1].Value !=
json_model.Id)
{
append("[INFO NOT MATCH] " + path);
nv.Add(path);
}
else
{
append("[VALID] " + path);
}
}
else
{
append("[FAIL INFO] " + path);
nv.Add(path);
}
}
}
}
}
catch (InvalidDataException)
{
append("[FAIL OPEN] " + path);
nv.Add(path);
}
cnt++;
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
PB.Value = cnt / (double)file_list.Count * 100;
}));
}
append($"{file_list.Count.ToString("#,#")}개의 파일 중 {nv.Count.ToString("#,#")}개의 파일이 유효하지 않습니다.");
File.WriteAllLines($"integrity-{DateTime.Now.Ticks}.txt", nv.ToArray());
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
BB.IsEnabled = true;
}));
}
19
Source : ZipListing.xaml.cs
with MIT License
from project-violet
with MIT License
from project-violet
private async void ProcessPath(string path)
{
FileIndexor fi = new FileIndexor();
await fi.ListingDirectoryAsync(path);
string root_directory = fi.RootDirectory;
Dictionary<string, ZipListingArticleModel> article_dic = new Dictionary<string, ZipListingArticleModel>();
foreach (var x in fi.Directories)
{
await Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
ProgressText.Text = x.Item1;
}));
foreach (var file in x.Item3)
{
try
{
if (!file.FullName.EndsWith(".zip")) continue;
var zipFile = ZipFile.Open(file.FullName, ZipArchiveMode.Read);
if (zipFile.GetEntry("Info.json") == null) continue;
using (var reader = new StreamReader(zipFile.GetEntry("Info.json").Open()))
{
var json_model = JsonConvert.DeserializeObject<HitomiJsonModel>(reader.ReadToEnd());
article_dic.Add(file.FullName.Substring(root_directory.Length), new ZipListingArticleModel { ArticleData = json_model, Size = file.Length, CreatedDate = file.CreationTime.ToString() });
}
}
catch (Exception e)
{
Monitor.Instance.Push($"[Zip Listing] {e.Message}");
}
}
}
model = new ZipListingModel();
model.RootDirectory = root_directory;
model.Tag = path;
model.ArticleList = article_dic.ToArray();
var tick = DateTime.Now.Ticks;
ZipListingModelManager.SaveModel($"ziplist-result-{tick}.json", model);
rate_filename = $"ziplist-result-{tick}-rating.json";
algorithm.Build(model);
article_list = article_dic.ToList();
elems.Clear();
article_list.ForEach(x => elems.Add(Tuple.Create(x, new Lazy<ZipListingElements>(() =>
{
return new ZipListingElements(root_directory + x.Key, x.Value.ArticleData, 0);
}))));
day_before = raws = elems;
sort_data(align_column, align_row);
await Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
CollectStatusPanel.Visibility = Visibility.Collapsed;
ArticleCount.Text = $"작품 {article_dic.Count.ToString("#,#")}개";
PageCount.Text = $"이미지 {article_list.Select(x => x.Value.ArticleData.Pages).Sum().ToString("#,#")}장";
max_page = article_dic.Count / show_elem_per_page;
initialize_page();
}));
stack_clear();
stack_push();
}
19
Source : ZipViewerElements.xaml.cs
with MIT License
from project-violet
with MIT License
from project-violet
private void ZipViewerElements_Loaded(object sender, RoutedEventArgs e)
{
Task.Run(() =>
{
try
{
zipFile = ZipFile.Open(zip_file_name, ZipArchiveMode.Read);
try
{
using (var reader = new StreamReader(zipFile.GetEntry("Info.json").Open()))
{
var model = JsonConvert.DeserializeObject<HitomiJsonModel>(reader.ReadToEnd());
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
replacedle.Text = model.replacedle;
Artist.Text = model.Artists != null ? model.Artists[0] : "";
}));
}
}
catch (Exception ex)
{
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
replacedle.Text = Path.GetFileNameWithoutExtension(zip_file_name);
Artist.Visibility = Visibility.Collapsed;
}));
}
var zipEntry = !zipFile.Entries[0].Name.EndsWith(".json") ? zipFile.Entries[0] : zipFile.Entries[1];
zipStream = zipEntry.Open();
Application.Current.Dispatcher.BeginInvoke(new Action(
delegate
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.DecodePixelWidth = 250;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = zipStream;
bitmap.EndInit();
bitmap.DownloadCompleted += Bitmap_DownloadCompleted;
Image.Source = bitmap;
}));
}
catch (Exception ex)
{
Monitor.Instance.Push(ex.Message);
Monitor.Instance.Push(ex.StackTrace);
}
});
}
19
Source : MainForm.cs
with MIT License
from project-violet
with MIT License
from project-violet
private void load_zip(string files)
{
IPicElement pe;
pe = new PicElement(this);
pe.Path = files;
pe.Label = Path.GetFileNameWithoutExtension(files);
using (var zip = ZipFile.Open(files, ZipArchiveMode.Read))
{
string tmp = Path.GetTempFileName();
if (!zip.Entries[0].Name.EndsWith(".json"))
zip.Entries[0].ExtractToFile(tmp, true);
else
zip.Entries[1].ExtractToFile(tmp, true);
try
{
pe.Log = JsonConvert.DeserializeObject<HitomiJsonModel>(new StreamReader(zip.GetEntry("Info.json").Open()).ReadToEnd());
if (pe.Log.Tags != null)
lock (tags)
{
foreach (var tag in pe.Log.Tags)
{
if (tags.ContainsKey(tag))
tags[tag] += 1;
else
tags.Add(tag, 1);
}
}
}
catch(Exception e)
{
}
pe.SetImageFromAddress(tmp, 150, 200);
}
pe.Font = this.Font;
Interlocked.Increment(ref count_load);
this.Post(() => Text = $"{prefix} [{count_load}/{max_load}]");
this.Post(() => flowLayoutPanel1.Controls.Add(pe as Control));
this.Post(() => SortThumbnail());
}
19
Source : UgoiraPostprocessor.cs
with MIT License
from project-violet
with MIT License
from project-violet
private void ugoira2gif(NetTask task)
{
Log.Logs.Instance.Push("[Postprocessor] Start ugoira to gif... " + task.Filename);
using (var file = File.OpenRead(task.Filename))
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
using (var entry = zip.GetEntry(Frames[0].File).Open())
using (var first_image = Image.Load(entry))
{
for (int i = 1; i < Frames.Count; i++)
{
using (var ientry = zip.GetEntry(Frames[i].File).Open())
using (var iimage = Image.Load(ientry))
{
var frame = iimage.Frames.RootFrame;
frame.Metadata.GetFormatMetadata(GifFormat.Instance).FrameDelay = Frames[i].Delay.Value / 10;
first_image.Frames.AddFrame(frame);
}
}
first_image.Save(Path.Combine(Path.GetDirectoryName(task.Filename), Path.GetFileName(task.Filename).Split('_')[0] + ".gif"), new GifEncoder());
}
File.Delete(task.Filename);
}
19
Source : PluginInfoPanel.xaml.cs
with GNU General Public License v3.0
from QL-Win
with GNU General Public License v3.0
from QL-Win
private static MemoryStream GetFileFromZip(string archive, string entry)
{
var ms = new MemoryStream();
try
{
using (var zip = ZipFile.Open(archive, ZipArchiveMode.Read))
{
using (var s = zip?.GetEntry(entry)?.Open())
{
s?.CopyTo(ms);
}
}
}
catch (Exception)
{
return ms;
}
ms.Position = 0;
return ms;
}
See More Examples