本文整理汇总了C#中System.IO.Compression.ZipArchive类的典型用法代码示例。如果您正苦于以下问题:C# ZipArchive类的具体用法?C# ZipArchive怎么用?C# ZipArchive使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ZipArchive类属于System.IO.Compression命名空间,在下文中一共展示了ZipArchive类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetDataDescriptors
public override IEnumerable<IDataDescriptor> GetDataDescriptors() {
List<ResourceRegressionDataDescriptor> descriptorList = new List<ResourceRegressionDataDescriptor>();
descriptorList.Add(new ChemicalOne());
descriptorList.Add(new Housing());
descriptorList.Add(new Tower());
descriptorList.Add(new Powermeter());
var solutionsArchiveName = GetResourceName(FileName + @"\.zip");
if (!String.IsNullOrEmpty(solutionsArchiveName)) {
using (var solutionsZipFile = new ZipArchive(GetType().Assembly.GetManifestResourceStream(solutionsArchiveName), ZipArchiveMode.Read)) {
IList<string> entries = new List<string>();
foreach (var curEntry in solutionsZipFile.Entries) {
entries.Add(curEntry.Name);
}
foreach (var entry in entries.OrderBy(x => x)) {
string prettyName = Path.GetFileNameWithoutExtension(entry);
ResourceRegressionDataDescriptor desc = descriptorList.Where(x => x.Name.Equals(prettyName)).FirstOrDefault();
if (desc != null) {
desc.ResourceName = entry;
yield return desc;
} else
throw new ArgumentNullException("No Descriptor could be found for this entry.");
}
}
}
}
示例2: UnZippingFiles
/// <summary>
/// 解压文件
/// </summary>
/// <param name="dirPath">要解压到的路径</param>
/// <param name="input">压缩文件数据</param>
internal static void UnZippingFiles(string dirPath, byte[] input)
{
//备份文件到dirPath下Backup文件夹下
ZippingBackupFiles(dirPath, dirPath + "Backup\\");
//覆盖文件
using (var zipStream = new MemoryStream(input))//将压缩文件信息初始化到内存流
{
using (var source = new ZipArchive(zipStream, ZipArchiveMode.Read))//读取压缩文件
{
foreach (var entry in source.Entries)
{
var fullPath = Path.GetFullPath(dirPath + entry.FullName);
if (fullPath.EndsWith("\\"))
{
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
}
}
else
{
using (var stream = entry.Open())
{
using (FileStream fileStream = File.Open(fullPath, FileMode.Create))
{
stream.CopyTo(fileStream);
}
}
}
}
}
}
}
示例3: GetRootFilePathAsync
public static async System.Threading.Tasks.Task<string> GetRootFilePathAsync(ZipArchive epubArchive)
{
//Checking if file exist
const string EPUB_CONTAINER_FILE_PATH = "META-INF/container.xml";
ZipArchiveEntry containerFileEntry = epubArchive.GetEntry(EPUB_CONTAINER_FILE_PATH);
string full_path = string.Empty;
if (containerFileEntry == null)
throw new Exception(String.Format("EPUB parsing error: {0} file not found in archive.", EPUB_CONTAINER_FILE_PATH));
//Loading container.xml to memmory...
using (Stream containerStream = containerFileEntry.Open())
{
// ...and trying to parse it in order to get the full path to the .opf file, like full-path="SomeFolder/SomeFileWithContent.opf"
full_path = await XmlUtils.GetFilePathAttributeAsync(containerStream);
}
//Checking if the problem exist...
if (full_path == "full-path attribute not found" || full_path == "Yes, rootfile not found...")
{
Debug.WriteLine(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
throw new Exception(string.Format("Content.opf path is FUBAR and the problem is: {0}", full_path));
}
return full_path;
//Initial code sucks and is not compatible with Win 8.1 runtime framework
/*
xmlNamespaceManager.AddNamespace("cns", "urn:oasis:names:tc:opendocument:xmlns:container");
XmlNode rootFileNode = containerDocument.DocumentElement.SelectSingleNode("/cns:container/cns:rootfiles/cns:rootfile", xmlNamespaceManager);
return rootFileNode.Attributes["full-path"].Value;
*/
}
示例4: Update
/// <summary>
/// Downloads the specified web driver version.
/// </summary>
/// <param name="version">The version to download.</param>
protected override void Update(string version)
{
using (var client = new WebClient())
using (var stream = client.OpenRead("http://chromedriver.storage.googleapis.com/" + version + "/chromedriver_win32.zip"))
using (var archive = new ZipArchive(stream))
archive.ExtractToDirectory(Path.Combine(ParentPath, version));
}
示例5: ZipRecursive
public static void ZipRecursive(
string rootDirectoryPath,
DirectoryInfo currentDirectoryInfo,
ZipArchive archive,
TextWriter hashWriter,
string hashName = ConstDefaultHashName)
{
rootDirectoryPath = NormalizePath(rootDirectoryPath);
foreach (var file in currentDirectoryInfo.GetFiles())
{
var entryName = file.FullName.Substring(rootDirectoryPath.Length);
using (var reader = file.OpenRead())
{
var hash = AddToArchive(entryName, reader, archive, hashName);
hashWriter.WriteLine(HashEntryFormat, hash, entryName);
Serilog.Log.Verbose("Added {filePath} to zip archive. MD5: {md5}", file.FullName, hash);
}
}
// recurse
foreach (var directory in currentDirectoryInfo.GetDirectories())
{
ZipRecursive(rootDirectoryPath, directory, archive, hashWriter, hashName);
}
}
示例6: Convert
public BitmapImage Convert([CanBeNull] string id) {
if (id == null) id = @"_";
BitmapImage bi;
if (Cache.TryGetValue(id, out bi)) return bi;
if (_archive == null) {
_archive = new ZipArchive(new MemoryStream(BinaryResources.Flags));
}
var entryStream = (_archive.GetEntry(id) ?? _archive.GetEntry(@"_"))?.Open();
if (entryStream == null) {
return null;
}
bi = new BitmapImage();
bi.BeginInit();
bi.CacheOption = BitmapCacheOption.OnLoad;
bi.StreamSource = entryStream.ReadAsMemoryStream();
bi.EndInit();
bi.Freeze();
Cache[id] = bi;
return bi;
}
示例7: ModelInfo
/// <summary>
/// Initializes a new instance of the <see cref="ModelInfo"/> class.
/// </summary>
/// <param name="fileInfo">The model file info.</param>
/// <exception cref="System.ArgumentNullException">fileInfo</exception>
/// <exception cref="System.IO.FileNotFoundException">The specified model file does not exist.</exception>
/// <exception cref="InvalidFormatException">Unable to load the specified model file.</exception>
public ModelInfo(FileInfo fileInfo) {
if (fileInfo == null)
throw new ArgumentNullException("fileInfo");
if (!fileInfo.Exists)
throw new FileNotFoundException("The specified model file does not exist.", fileInfo.FullName);
File = fileInfo;
Name = Path.GetFileNameWithoutExtension(fileInfo.Name);
try {
using (var zip = new ZipArchive(fileInfo.OpenRead(), ZipArchiveMode.Read)) {
foreach (var entry in zip.Entries) {
if (entry.Name != ArtifactProvider.ManifestEntry)
continue;
using (var stream = entry.Open()) {
Manifest = (Properties)Properties.Deserialize(stream);
break;
}
}
}
} catch (Exception ex) {
throw new InvalidFormatException("Unable to load the specified model file.", ex);
}
}
示例8: CheckAndUpdateIfNeededInner
protected override async Task<bool> CheckAndUpdateIfNeededInner() {
if (InstalledVersion == null) return false;
var data = await CmApiProvider.GetDataAsync($"locales/update/{SettingsHolder.Locale.LocaleName}/{InstalledVersion}");
if (data == null) {
LatestError = ToolsStrings.BaseUpdater_CannotDownloadInformation;
Logging.Warning("Cannot get locales/update");
return false;
}
if (data.Length == 0) {
return false;
}
try {
LocalePackageManifest manifest;
using (var memory = new MemoryStream(data))
using (var updateZip = new ZipArchive(memory)) {
manifest = LocalePackageManifest.FromArchive(updateZip);
if (manifest == null) throw new Exception("Manifest is missing");
}
var package = FilesStorage.Instance.GetFilename("Locales", manifest.Id + ".pak");
await FileUtils.WriteAllBytesAsync(package, data);
Logging.Write("Locale updated");
InstalledVersion = manifest.Version;
return true;
} catch (Exception e) {
Logging.Warning("Cannot update locale: " + e);
return false;
}
}
示例9: LoadAndInstall
private async Task<bool> LoadAndInstall() {
if (_isInstalling) return false;
_isInstalling = true;
try {
var data = await CmApiProvider.GetDataAsync("data/latest");
if (data == null) throw new InformativeException(ToolsStrings.AppUpdater_CannotLoad, ToolsStrings.Common_MakeSureInternetWorks);
string installedVersion = null;
await Task.Run(() => {
var location = FilesStorage.Instance.Combine(FilesStorage.DataDirName);
Directory.Delete(location, true);
using (var stream = new MemoryStream(data, false))
using (var archive = new ZipArchive(stream)) {
installedVersion = VersionFromData(archive.GetEntry(@"Manifest.json").Open().ReadAsStringAndDispose());
archive.ExtractToDirectory(location);
}
});
InstalledVersion = installedVersion;
Logging.Write("Data loaded: " + InstalledVersion);
return true;
} catch (Exception e) {
NonfatalError.Notify(ToolsStrings.ContentSyncronizer_CannotLoadContent, ToolsStrings.ContentSyncronizer_CannotLoadContent_Commentary, e);
} finally {
_isInstalling = false;
}
return false;
}
示例10: ImportFiles
private void ImportFiles(ZipArchive file, string path)
{
var enumerable = file.Entries.Where(a => a.FullName.StartsWith("data/"));
foreach (var zipArchiveEntry in enumerable)
{
var directoryName = Path.GetDirectoryName(zipArchiveEntry.FullName);
if (directoryName != null)
{
string virtualPath = "." +
(directoryName.Replace("\\", "/") + "/" +
Path.GetFileNameWithoutExtension(zipArchiveEntry.FullName)).Substring(4);
var extension = Path.GetExtension(zipArchiveEntry.FullName);
if (extension != null && !Root.Information.DeletedFiles.Contains(virtualPath))
{
string hash = extension.Substring(1);
if (Root.Children.All(a => a.VirtualPath != virtualPath))
Root.Children.Add(new BackupFile
{
Name =
Path.GetFileNameWithoutExtension(
Path.GetFileName(zipArchiveEntry.FullName)),
FileHash = hash,
VirtualPath = virtualPath,
ArchivePath = path
});
}
}
}
}
示例11: CreateTestPackageStream
private static Stream CreateTestPackageStream()
{
var packageStream = new MemoryStream();
using (var packageArchive = new ZipArchive(packageStream, ZipArchiveMode.Create, true))
{
var nuspecEntry = packageArchive.CreateEntry("TestPackage.nuspec", CompressionLevel.Fastest);
using (var streamWriter = new StreamWriter(nuspecEntry.Open()))
{
streamWriter.WriteLine(@"<?xml version=""1.0""?>
<package xmlns=""http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd"">
<metadata>
<id>TestPackage</id>
<version>0.0.0.1</version>
<title>Package A</title>
<authors>ownera, ownerb</authors>
<owners>ownera, ownerb</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description>package A description.</description>
<language>en-US</language>
<projectUrl>http://www.nuget.org/</projectUrl>
<iconUrl>http://www.nuget.org/</iconUrl>
<licenseUrl>http://www.nuget.org/</licenseUrl>
<dependencies />
</metadata>
</package>");
}
packageArchive.CreateEntry("content\\HelloWorld.cs", CompressionLevel.Fastest);
}
packageStream.Position = 0;
return packageStream;
}
示例12: ButtonRestore_Click
private async void ButtonRestore_Click(object sender, RoutedEventArgs e)
{
var selected = ListBoxBackups.SelectedItem as BackupFile;
if(selected != null)
{
var result =
await
Helper.MainWindow.ShowMessageAsync("Restore backup " + selected.DisplayName,
"This can not be undone! Make sure you have a current backup (if necessary). To create one, CANCEL and click \"CREATE NEW\".",
MessageDialogStyle.AffirmativeAndNegative);
if(result == MessageDialogResult.Affirmative)
{
var archive = new ZipArchive(selected.FileInfo.OpenRead(), ZipArchiveMode.Read);
archive.ExtractToDirectory(Config.Instance.DataDir, true);
Config.Load();
Config.Save();
DeckList.Load();
DeckList.Save();
DeckStatsList.Load();
DeckStatsList.Save();
DefaultDeckStats.Load();
DefaultDeckStats.Save();
Helper.MainWindow.ShowMessage("Success", "Please restart HDT for this to take effect.");
}
}
}
示例13: ProcessFolder
static void ProcessFolder(XElement folder, ZipArchive theZip, string folderRelativePath)
{
string targetDirectory = (string)folder.Attribute("Name");
string currentRelativePath = AppendRelativePath(folderRelativePath, targetDirectory);
Console.WriteLine("Processing folder " + currentRelativePath);
foreach (var component in folder.Elements(Namespace + ElementNameComponent))
{
foreach (var file in component.Elements(Namespace + ElementNameFile))
{
string source = (string)file.Attribute("Source");
string name = (string)file.Attribute("Name");
theZip.CreateEntryFromFile(RelativePathToolToSetupFolder + source,
AppendRelativePath(currentRelativePath, name),
CompressionLevel.Optimal);
}
}
foreach (var secondaryFolder in folder.Elements(Namespace + ElementNameDirectory))
{
ProcessFolder(secondaryFolder, theZip, currentRelativePath);
}
}
示例14: InstallPackageAsync
public async override Task<bool> InstallPackageAsync(Packaging.Core.PackageIdentity packageIdentity, System.IO.Stream packageStream,
INuGetProjectContext nuGetProjectContext, CancellationToken token)
{
if (!packageStream.CanSeek)
{
throw new ArgumentException(NuGet.ProjectManagement.Strings.PackageStreamShouldBeSeekable);
}
nuGetProjectContext.Log(MessageLevel.Info, Strings.InstallingPackage, packageIdentity);
packageStream.Seek(0, SeekOrigin.Begin);
var zipArchive = new ZipArchive(packageStream);
PackageReader packageReader = new PackageReader(zipArchive);
var packageSupportedFrameworks = packageReader.GetSupportedFrameworks();
var projectFrameworks = _project.GetSupportedFrameworksAsync(token)
.Result
.Select(f => NuGetFramework.Parse(f.FullName));
var args = new Dictionary<string, object>();
args["Frameworks"] = projectFrameworks.Where(
projectFramework =>
IsCompatible(projectFramework, packageSupportedFrameworks)).ToArray();
await _project.InstallPackageAsync(
new NuGetPackageMoniker
{
Id = packageIdentity.Id,
Version = packageIdentity.Version.ToNormalizedString()
},
args,
logger: null,
progress: null,
cancellationToken: token);
return true;
}
示例15: ExtractEntries
public string[] ExtractEntries(string sourceArchiveFileName, string destinationDirectoryName)
{
using (var archiveStream = _fileSystem.OpenFile(sourceArchiveFileName, FileMode.Open, FileAccess.Read))
using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Read))
{
foreach (var entry in archive.Entries)
{
var path = PathHelper.Combine(destinationDirectoryName, entry.FullName);
if (string.IsNullOrEmpty(entry.Name))
{
// is a directory
if (!_fileSystem.DirExists(path))
_fileSystem.CreateDir(path);
continue;
}
else
{
var dir = PathHelper.GetParent(path);
if (!_fileSystem.DirExists(dir))
_fileSystem.CreateDir(dir);
}
using (var entryStream = entry.Open())
{
using (var fileStream = _fileSystem.OpenFile(path, FileMode.Create, FileAccess.Write))
{
entryStream.CopyTo(fileStream);
fileStream.Flush();
}
}
}
var entries = archive.Entries.Select(x => x.FullName).ToArray();
return entries;
}
}