本文整理汇总了C#中System.IO.Compression.ZipArchive.CreateEntry方法的典型用法代码示例。如果您正苦于以下问题:C# ZipArchive.CreateEntry方法的具体用法?C# ZipArchive.CreateEntry怎么用?C# ZipArchive.CreateEntry使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Compression.ZipArchive
的用法示例。
在下文中一共展示了ZipArchive.CreateEntry方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
示例2: ZipPackage
private void ZipPackage(PassGeneratorRequest request)
{
using (MemoryStream zipToOpen = new MemoryStream())
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update, true))
{
foreach (KeyValuePair<PassbookImage, byte[]> image in request.Images)
{
ZipArchiveEntry imageEntry = archive.CreateEntry(image.Key.ToFilename());
using (BinaryWriter writer = new BinaryWriter(imageEntry.Open()))
{
writer.Write(image.Value);
writer.Flush();
}
}
foreach (KeyValuePair<string, byte[]> localization in localizationFiles)
{
ZipArchiveEntry localizationEntry = archive.CreateEntry(string.Format ("{0}.lproj/pass.strings", localization.Key.ToLower()));
using (BinaryWriter writer = new BinaryWriter(localizationEntry.Open()))
{
writer.Write(localization.Value);
writer.Flush();
}
}
ZipArchiveEntry PassJSONEntry = archive.CreateEntry(@"pass.json");
using (BinaryWriter writer = new BinaryWriter(PassJSONEntry.Open()))
{
writer.Write(passFile);
writer.Flush();
}
ZipArchiveEntry ManifestJSONEntry = archive.CreateEntry(@"manifest.json");
using (BinaryWriter writer = new BinaryWriter(ManifestJSONEntry.Open()))
{
writer.Write(manifestFile);
writer.Flush();
}
ZipArchiveEntry SignatureEntry = archive.CreateEntry(@"signature");
using (BinaryWriter writer = new BinaryWriter(SignatureEntry.Open()))
{
writer.Write(signatureFile);
writer.Flush();
}
}
pkPassFile = zipToOpen.ToArray();
zipToOpen.Flush();
}
}
示例3: Execute
public override bool Execute()
{
// Originally taken from https://peteris.rocks/blog/creating-release-zip-archive-with-msbuild/
// Then modified not to be inline anymore
try
{
using (Stream zipStream = new FileStream(Path.GetFullPath(OutputFilename), FileMode.Create, FileAccess.Write))
using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
foreach (ITaskItem fileItem in Files)
{
string filename = fileItem.ItemSpec;
using (Stream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
using (Stream fileStreamInZip = archive.CreateEntry(new FileInfo(filename).Name).Open())
fileStream.CopyTo(fileStreamInZip);
}
}
return true;
}
catch (Exception ex)
{
Log.LogErrorFromException(ex);
return false;
}
}
示例4: Archive
public static ZipFileMock Archive(string sourceDirectoryName, string destinationArchiveFileName, params FileMock[] files)
{
var bytes = new byte[0];
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
var relativePath = PathHelper.Subtract(file.Path, sourceDirectoryName);
var entry = archive.CreateEntry(relativePath);
using (var entryStream = entry.Open())
{
entryStream.Write(file.Bytes, 0, file.Bytes.Length);
entryStream.Flush();
}
}
}
// Fix for "invalid zip archive"
using ( var fileStream = new MemoryStream() )
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(fileStream);
bytes = fileStream.ToArray();
}
}
var zipFile = new ZipFileMock(destinationArchiveFileName, bytes, files);
return zipFile;
}
示例5: ParseZip
public void ParseZip(FileStream zipToOpen, FileStream zipToWrite, Predicate<string> fileNameFilter, Action<Stream, Stream> parseAction, Action<int> processingPercentage)
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read),
newArchive = new ZipArchive(zipToWrite, ZipArchiveMode.Create))
{
int entriesDone = 0;
int entriesCount = archive.Entries.Count;
foreach (ZipArchiveEntry entry in archive.Entries)
{
processingPercentage(100 * entriesDone++ / entriesCount);
if (fileNameFilter(entry.Name))
{
ZipArchiveEntry newEntry = newArchive.CreateEntry(entry.FullName);
using (Stream stream = entry.Open(),
newStream = newEntry.Open())
{
parseAction(stream, newStream);
}
}
}
}
}
示例6: ExprortFromDb
public FileResult ExprortFromDb()
{
try
{
if (IocHelper.CurrentToggle != "db")
{
throw new Exception("Экспорт возможен только из БД");
}
var helper = new IocHelper();
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry("db_export.xml", CompressionLevel.Optimal);
using (var entryStream = demoFile.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
streamWriter.Write(helper.ArticleService.ExportFromDb());
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
return File(memoryStream.ToArray(), "application/zip", "db_export.zip");
}
}
catch (Exception e)
{
throw new HttpException(500, e.Message);
}
}
示例7: ZipByteArray
/// <summary>
/// Zip's up a list of files where you only have the byte array. So everything is in memory, and you want to zip it up and send it for download or do something else with a byte array
/// </summary>
/// <param name="FilesToZip">Files To Zip Up. Key is the file name and the value is the byte array which contains the file</param>
/// <returns>The Zipped up files in a byte array</returns>
public static byte[] ZipByteArray(IDictionary<string, byte[]> FilesToZip)
{
//create the memory stream which the zip will be created with
using (var MemoryStreamToCreateZipWith = new MemoryStream())
{
//declare the working zip archive
using (var WorkingZipArchive = new ZipArchive(MemoryStreamToCreateZipWith, ZipArchiveMode.Update, false))
{
//loop through each of the files and add it to the working zip
foreach (var FileToZipUp in FilesToZip)
{
//Create a zip entry for each attachment
var ZipEntry = WorkingZipArchive.CreateEntry(FileToZipUp.Key);
//Get the stream of the attachment
using (var FileToZipUpInMemoryStream = new MemoryStream(FileToZipUp.Value))
{
//grab the memory stream from the zip entry
using (var ZipEntryStream = ZipEntry.Open())
{
//Copy the attachment stream to the zip entry stream
FileToZipUpInMemoryStream.CopyTo(ZipEntryStream);
}
}
}
}
//all done, so go return the byte array which contains the zipped up file bytes
return MemoryStreamToCreateZipWith.ToArray();
}
}
示例8: CompressUsingMemory
private void CompressUsingMemory()
{
var item = GetNextItem();
while (item != null) {
using (var strm = new MemoryStream()) {
using (var archive = new ZipArchive(strm, ZipArchiveMode.Create, true)) {
var cfg = new Config(item.Source) {ScanType = ScanType.FilesOnly};
cfg.OnFile += (o, a) => {
var entryPath = a.Path.Replace(item.Source + "\\", "");
var entry = archive.CreateEntry(entryPath, CompressionLevel.Fastest);
using (var entryStream = entry.Open()) {
using (var fileStream = File.OpenRead(a.Path)) {
fileStream.CopyTo(entryStream);
fileStream.Close();
}
entryStream.Flush();
entryStream.Close();
}
};
Snarfzer.NewScanner().Start(cfg);
}
strm.Position = 0;
using (var outstream = File.OpenWrite(item.Dest))
strm.CopyTo(outstream);
}
item = GetNextItem();
}
}
示例9: Zip
public static byte[] Zip(List<Tuple<string, byte[]>> files)
{
using (var compressedFileStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
{
foreach (var file in files)
{
//Create a zip entry for each attachment
var zipEntry = zipArchive.CreateEntry(file.Item1);
//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(file.Item2))
{
using (var zipEntryStream = zipEntry.Open())
{
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
}
return compressedFileStream.ToArray();
}
}
示例10: AddToArchive
private static string AddToArchive(string entryName, Stream inputStream, ZipArchive zipArchive, string hashName)
{
var entry = zipArchive.CreateEntry(entryName);
HashAlgorithm hashAlgorithm = null;
BinaryWriter zipEntryWriter = null;
try
{
hashAlgorithm = HashAlgorithm.Create(hashName);
zipEntryWriter = new BinaryWriter(entry.Open());
var readBuffer = new byte[StreamReadBufferSize];
int bytesRead;
while ((bytesRead = inputStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
zipEntryWriter.Write(readBuffer, 0, bytesRead);
hashAlgorithm.TransformBlock(readBuffer, 0, bytesRead, readBuffer, 0);
}
hashAlgorithm.TransformFinalBlock(readBuffer, 0, 0);
var hashHexStringBuilder = new StringBuilder();
foreach (byte hashByte in hashAlgorithm.Hash)
{
hashHexStringBuilder.Append(hashByte.ToString("x2"));
}
return hashHexStringBuilder.ToString();
}
finally
{
hashAlgorithm.SafeDispose();
zipEntryWriter.SafeDispose();
}
}
示例11: GenerateZip
public void GenerateZip(Models.WordList wordList, Stream outputStream)
{
using (ZipArchive zip = new ZipArchive(outputStream, ZipArchiveMode.Create, true))
{
ZipArchiveEntry wordsEntry = zip.CreateEntry(ZipWordListEntryName);
GenerateXml(wordList, wordsEntry.Open());
}
}
示例12: ContentDialog_PrimaryButtonClick
private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) {
var selected = new List<object>(TileList.SelectedItems);
var picker = new FileSavePicker();
picker.SuggestedFileName = $"export_{DateTime.Now.ToString(DateTimeFormatInfo.CurrentInfo.ShortDatePattern)}";
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
picker.FileTypeChoices.Add("Tiles file", new List<string>() { ".tiles" });
var file = await picker.PickSaveFileAsync();
if (file != null) {
CachedFileManager.DeferUpdates(file);
await FileIO.WriteTextAsync(file, "");
using (var stream = await file.OpenStreamForWriteAsync())
using (var zip = new ZipArchive(stream, ZipArchiveMode.Update)) {
while (zip.Entries.Count > 0) {
zip.Entries[0].Delete();
}
using (var metaStream = zip.CreateEntry("tiles.json").Open())
using (var writer = new StreamWriter(metaStream)) {
var array = new JsonArray();
selected.ForEachWithIndex<SecondaryTile>((item, index) => {
var objet = new JsonObject();
objet.Add("Name", item.DisplayName);
objet.Add("Arguments", item.Arguments);
objet.Add("TileId", item.TileId);
objet.Add("IconNormal", item.VisualElements.ShowNameOnSquare150x150Logo);
objet.Add("IconWide", item.VisualElements.ShowNameOnWide310x150Logo);
objet.Add("IconBig", item.VisualElements.ShowNameOnSquare310x310Logo);
array.Add(objet);
if (item.VisualElements.Square150x150Logo.LocalPath != DEFAULT_URI) {
var path = ApplicationData.Current.LocalFolder.Path + Uri.UnescapeDataString(item.VisualElements.Square150x150Logo.AbsolutePath.Substring(6));
zip.CreateEntryFromFile(path, item.TileId + "/normal");
}
});
writer.WriteLine(array.Stringify());
}
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if(status == FileUpdateStatus.Complete) {
var folder = await file.GetParentAsync();
await new MessageDialog("Speichern erfolgreich").ShowAsync();
} else {
await new MessageDialog("Speichern fehlgeschlagen").ShowAsync();
}
Debug.WriteLine(status);
}
}
}
示例13: SaveImage
/// <summary>
/// Save an image to zip archive
/// </summary>
/// <param name="image">The image to save</param>
/// <param name="archive">The archive to save to</param>
public void SaveImage(Image image, ZipArchive archive)
{
// Create file in zip
ZipArchiveEntry imageEntry = archive.CreateEntry(StringResources.PATH_IMAGE_DIR + Path);
using (Stream stream = imageEntry.Open())
{
// Save the image
image.Save(stream, ImageFormat.Png);
}
}
示例14: Start
public void Start(Options options) {
foreach (var file in options.InputFiles) {
string fileName = Path.GetFileName(file);
using (var stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite)) {
using (var zipFile = new ZipArchive(stream, ZipArchiveMode.Update)) {
ZipArchiveEntry data = zipFile.Entries.Where(x => x.FullName.Equals("data.xml")).FirstOrDefault();
ZipArchiveEntry typecache = zipFile.Entries.Where(x => x.FullName.Equals("typecache.xml")).FirstOrDefault();
string tmp = null;
XmlDocument doc = new XmlDocument();
using (var s = new StreamReader(data.Open())) {
tmp = s.ReadToEnd();
}
doc.LoadXml(tmp);
var primitiveNode = doc.SelectNodes("//PRIMITIVE[contains(.,'GEArtificialAntEvaluator')]");
if (primitiveNode.Count > 1 || primitiveNode.Count <= 0) {
Helper.printToConsole("No GEArtificialAntEvaluator found", fileName);
continue;
}
primitiveNode[0].ParentNode.ParentNode.RemoveChild(primitiveNode[0].ParentNode);
string name = data.FullName;
data.Delete();
data = zipFile.CreateEntry(name);
using (var s = new StreamWriter(data.Open())) {
doc.Save(s);
}
using (var s = new StreamReader(typecache.Open())) {
tmp = s.ReadToEnd();
}
tmp = string.Join(Environment.NewLine, tmp.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Where(x => !x.Contains("GrammaticalEvolution")).ToArray());
name = typecache.FullName;
typecache.Delete();
typecache = zipFile.CreateEntry(name);
using (var s = new StreamWriter(typecache.Open())) {
s.Write(tmp);
}
}
}
}
}
示例15: Set
public void Set(string key, object value)
{
using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate))
{
using (ZipArchive archive = new ZipArchive(fs, ZipArchiveMode.Create))
{
var entry = archive.CreateEntry(key);
Writer.Write(entry.Open(), value);
}
}
}