public override void Write(Package package) { MemoryStream memoryStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(memoryStream); this.WriteFolder(zipStream, string.Empty, (PackageFolder)package); ((DeflaterOutputStream)zipStream).Finish(); memoryStream.WriteTo(this.output); }
/// <summary> /// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="content"/> /// and having the specified <paramref name="fileNameForZip" />. The archive is created in memory and is not stored on disk. /// </summary> /// <param name="content">The text to be added to the ZIP archive.</param> /// <param name="fileNameForZip">The name to be given to the <paramref name="content" /> within the ZIP archive.</param> /// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified <paramref name="content" />.</returns> public static Stream CreateZipStream(string content, string fileNameForZip) { MemoryStream ms = new MemoryStream(); ZipOutputStream zos = new ZipOutputStream(ms); zos.SetLevel(ZIP_COMPRESSION_LEVEL); AddFileZipEntry(zos, content, fileNameForZip); zos.Finish(); return ms; }
private void WriteFolder(ZipOutputStream zipStream, string path, PackageFolder folder) { foreach (PackageEntry packageEntry in (IEnumerable<PackageEntry>) folder.GetEntries()) { if (packageEntry is PackageFile) { zipStream.PutNextEntry(new ZipEntry(this.CombinePath(path, packageEntry.Name))); byte[] data = ((PackageFile)packageEntry).Data; ((Stream)zipStream).Write(data, 0, data.Length); zipStream.CloseEntry(); } if (packageEntry is PackageFolder) this.WriteFolder(zipStream, this.CombinePath(path, packageEntry.Name), (PackageFolder)packageEntry); } }
public MemoryStream Create(List <Arquivo.Arquivo> arquivos) { MemoryStream outputMemStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression ZipEntry newEntry = null; try { foreach (var item in arquivos) { newEntry = new ZipEntry(String.Format("{0}.{1}", item.Nome, item.Extensao)); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); if (!item.Buffer.CanRead && (item.Buffer is MemoryStream)) { MemoryStream msTemp = new MemoryStream((item.Buffer as MemoryStream).ToArray()); item.Buffer.Close(); item.Buffer.Dispose(); item.Buffer = msTemp; } StreamUtils.Copy(item.Buffer, zipStream, new byte[4096]); zipStream.CloseEntry(); if (item != null) { item.Buffer.Close(); } zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. // Must finish the ZipOutputStream before using outputMemStream. } } finally { if (zipStream != null) { zipStream.Close(); } } outputMemStream.Position = 0; return(outputMemStream); /* * // Alternative outputs: * // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory. * byte[] byteArrayOut = outputMemStream.ToArray(); * * // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself. * byte[] byteArrayOut = outputMemStream.GetBuffer(); * long len = outputMemStream.Length; */ }
/// <summary> /// Adds the file associated with the <paramref name="mediaObject"/> to the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="mediaObject">The media object to be added to the ZIP archive.</param> /// <param name="imageSize">Size of the image to add to the ZIP archive. This parameter applies only to <see cref="Image"/> /// media objects.</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only when <paramref name="mediaObject"/> is an <see cref="Image"/>.</param> private static void AddFileZipEntry(ZipOutputStream zos, IGalleryObject mediaObject, DisplayObjectType imageSize, string basePath, bool applyWatermark) { // Get the path to the file we'll be adding to the zip file. string filePath = GetMediaFilePath(mediaObject, imageSize); // Always use the file name of the original for naming the entry in the zip file. string fileNameForZip = mediaObject.Original.FileNamePhysicalPath; if ((!String.IsNullOrEmpty(filePath)) && (!String.IsNullOrEmpty(fileNameForZip))) { AddFileZipEntry(zos, filePath, fileNameForZip, basePath, (mediaObject is Image), applyWatermark); } }
/// <summary> /// Create a zip archive sending output to the <paramref name="outputStream"/> passed. /// </summary> /// <param name="outputStream">The stream to write archive data to.</param> /// <param name="sourceDirectory">The directory to source files from.</param> /// <param name="recurse">True to recurse directories, false for no recursion.</param> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter">directory filter</see> to apply.</param> public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; using ( outputStream_ = new ZipOutputStream(outputStream) ) { if (password_ != null) { outputStream_.Password = password_; } var scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += ProcessFile; if ( CreateEmptyDirectories ) { scanner.ProcessDirectory += ProcessDirectory; } if (events_ != null) { if ( events_.FileFailure != null ) { scanner.FileFailure += events_.FileFailure; } if ( events_.DirectoryFailure != null ) { scanner.DirectoryFailure += events_.DirectoryFailure; } } scanner.Scan(sourceDirectory, recurse); } }
/// <overloads>Adds an object to the ZIP archive.</overloads> /// <summary> /// Adds the file associated with the <paramref name="mediaObject"/> to the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="mediaObject">The media object to be added to the ZIP archive.</param> /// <param name="mediaSize">Size of the media file to add to the ZIP archive.</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only when <paramref name="mediaObject"/> is an <see cref="Image"/>.</param> private static void AddFileZipEntry(ZipOutputStream zos, IGalleryObject mediaObject, DisplayObjectType mediaSize, string basePath, bool applyWatermark) { // Get the path to the file we'll be adding to the zip file. string filePath = GetMediaFilePath(mediaObject, mediaSize); // Get the name we want to use for the file we are adding to the zip file. string fileNameForZip = GetMediaFileNameForZip(mediaObject, mediaSize); if ((!String.IsNullOrEmpty(filePath)) && (!String.IsNullOrEmpty(fileNameForZip))) { AddFileZipEntry(zos, filePath, fileNameForZip, basePath, (mediaObject is Image), applyWatermark, mediaObject.GalleryId); } }
public static void TestZipped() { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(100000); t1 = DateTime.Now; XmlDocumentSerializationInfo info = new XmlDocumentSerializationInfo(); info.AddValue("FooNode",o); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(7); info.Doc.Save(ZipStream); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmltest03.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlDocument doc3 = new XmlDocument(); doc3.Load(zipinpstream); XmlDocumentSerializationInfo info3 = new XmlDocumentSerializationInfo(doc3); Foo o3 = (Foo)info3.GetValue(null); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); }
static void AddToZip(ZipOutputStream zip, string filename) { AddToZip(zip, filename, filename); }
public Stream GetInstallFileStream(string packageFileDownloadUrl) { Initialize(); PackageDescription packageDescription = null; ExtraInfo extraInfo = null; foreach (List <KeyValuePair <PackageDescription, ExtraInfo> > packageDescriptions in _packageDescriptions.Values) { KeyValuePair <PackageDescription, ExtraInfo>?q = (from desc in packageDescriptions where desc.Key.PackageFileDownloadUrl == packageFileDownloadUrl select desc).FirstOrDefault(); if (q != null) { packageDescription = q.Value.Key; extraInfo = q.Value.Value; break; } } XElement rootElement = new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInstallerElementName), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageRequirementsElementName), new XAttribute(PackageSystemSettings.MinimumCompositeVersionAttributeName, packageDescription.MinCompositeVersionSupported), new XAttribute(PackageSystemSettings.MaximumCompositeVersionAttributeName, packageDescription.MaxCompositeVersionSupported) ), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageInformationElementName), new XAttribute(PackageSystemSettings.IdAttributeName, packageDescription.Id), new XAttribute(PackageSystemSettings.NameAttributeName, packageDescription.Name), new XAttribute(PackageSystemSettings.GroupNameAttributeName, packageDescription.GroupName), new XAttribute(PackageSystemSettings.AuthorAttributeName, packageDescription.Vendor), new XAttribute(PackageSystemSettings.WebsiteAttributeName, packageDescription.ReadMoreUrl), new XAttribute(PackageSystemSettings.VersionAttributeName, packageDescription.PackageVersion), new XAttribute(PackageSystemSettings.CanBeUninstalledAttributeName, extraInfo.CanBeUninstalled), new XAttribute(PackageSystemSettings.SystemLockingAttributeName, extraInfo.SystemLockingType.Serialize()), new XAttribute(PackageSystemSettings.FlushOnCompletionAttributeName, extraInfo.FlushOnCompletion), new XAttribute(PackageSystemSettings.ReloadConsoleOnCompletionAttributeName, extraInfo.ReloadConsoleOnCompletion), packageDescription.Description ), new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallersElementName)) ); XDocument doc = new XDocument(rootElement); string content = doc.GetDocumentAsString(); UTF8Encoding encoding = new UTF8Encoding(); byte[] buffer = encoding.GetBytes(content); MemoryStream outputStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(outputStream); Crc32 crc = new Crc32(); crc.Update(buffer); ZipEntry zipEntry = new ZipEntry("install.xml"); zipEntry.Size = buffer.Length; zipEntry.Crc = crc.Value; zipEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(zipEntry); zipStream.Write(buffer, 0, buffer.Length); zipStream.Finish(); outputStream.Seek(0, SeekOrigin.Begin); return(outputStream); }
/// <summary> /// Packages the specified items. /// </summary> /// <param name="result">The result.</param> /// <param name="zipStream">The zip stream.</param> /// <returns>The name of the files that were packaged.</returns> public IEnumerable <string> Package(IIntegrationResult result, ZipOutputStream zipStream) { var fileSystem = this.FileSystem ?? new SystemIoFileSystem(); var baseFolder = result.WorkingDirectory; var files = this.GenerateFileList(result, fileSystem); var actualFiles = new List <string>(); foreach (var fullName in files) { var fileInfo = new FileInfo(fullName); if (fileSystem.FileExists(fullName)) { // Generate the name of the file to store in the package var targetFileName = string.IsNullOrEmpty(this.TargetFileName) ? fileInfo.Name : this.TargetFileName; var targetPath = this.TargetFolder; if (string.IsNullOrEmpty(targetPath)) { if (fileInfo.DirectoryName.StartsWith(baseFolder)) { targetPath = fileInfo.DirectoryName.Substring(baseFolder.Length); } else { targetPath = fileInfo.DirectoryName; } } // Clean the target name if (targetPath.StartsWith(Path.DirectorySeparatorChar + string.Empty)) { targetPath = targetPath.Substring(1); } // Add the entry to the file file var entry = new ZipEntry(ZipEntry.CleanName(Path.Combine(targetPath, targetFileName))); entry.Size = fileSystem.GetFileLength(fullName); // zipentry date set to last changedate, other it contains not the right filedate. // added 10.11.2010 by rolf eisenhut entry.DateTime = fileSystem.GetLastWriteTime(fullName); zipStream.PutNextEntry(entry); var buffer = new byte[8182]; // Add the actual file - just tranfer the data from one stream to another var inputStream = fileSystem.OpenInputStream(fullName); try { var dataLength = 1; while (dataLength > 0) { dataLength = inputStream.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, dataLength); } } finally { inputStream.Close(); } // Finish up and return the file name so it can be used in the manifest zipStream.CloseEntry(); actualFiles.Add(fullName); } } return(actualFiles); }
static int Main(string[] args) { IKVM.Internal.Tracer.EnableTraceConsoleListener(); IKVM.Internal.Tracer.EnableTraceForDebug(); string assemblyNameOrPath = null; bool continueOnError = false; bool autoLoadSharedClassLoaderAssemblies = false; List <string> references = new List <string>(); List <string> libpaths = new List <string>(); bool nostdlib = false; bool bootstrap = false; string outputFile = null; bool forwarders = false; foreach (string s in args) { if (s.StartsWith("-") || assemblyNameOrPath != null) { if (s == "-serialver") { Console.Error.WriteLine("The -serialver option is deprecated and will be removed in the future. Use -japi instead."); includeSerialVersionUID = true; } else if (s == "-japi") { includeSerialVersionUID = true; includeNonPublicInterfaces = true; includeNonPublicMembers = true; } else if (s == "-skiperror") { continueOnError = true; } else if (s == "-shared") { autoLoadSharedClassLoaderAssemblies = true; } else if (s.StartsWith("-r:") || s.StartsWith("-reference:")) { references.Add(s.Substring(s.IndexOf(':') + 1)); } else if (s == "-nostdlib") { nostdlib = true; } else if (s.StartsWith("-lib:")) { libpaths.Add(s.Substring(5)); } else if (s == "-bootstrap") { bootstrap = true; } else if (s.StartsWith("-out:")) { outputFile = s.Substring(5); } else if (s.StartsWith("-namespace:")) { namespaces.Add(s.Substring(11) + "."); } else if (s == "-forwarders") { forwarders = true; } else if (s == "-parameters") { includeParameterNames = true; } else { // unrecognized option, or multiple assemblies, print usage message and exit assemblyNameOrPath = null; break; } } else { assemblyNameOrPath = s; } } if (assemblyNameOrPath == null) { Console.Error.WriteLine(GetVersionAndCopyrightInfo()); Console.Error.WriteLine(); Console.Error.WriteLine("usage: ikvmstub [-options] <assemblyNameOrPath>"); Console.Error.WriteLine(); Console.Error.WriteLine("options:"); Console.Error.WriteLine(" -out:<outputfile> Specify the output filename"); Console.Error.WriteLine(" -reference:<filespec> Reference an assembly (short form -r:<filespec>)"); Console.Error.WriteLine(" -japi Generate jar suitable for comparison with japitools"); Console.Error.WriteLine(" -skiperror Continue when errors are encountered"); Console.Error.WriteLine(" -shared Process all assemblies in shared group"); Console.Error.WriteLine(" -nostdlib Do not reference standard libraries"); Console.Error.WriteLine(" -lib:<dir> Additional directories to search for references"); Console.Error.WriteLine(" -namespace:<ns> Only include types from specified namespace"); Console.Error.WriteLine(" -forwarders Export forwarded types too"); Console.Error.WriteLine(" -parameters Emit Java 8 classes with parameter names"); return(1); } if (File.Exists(assemblyNameOrPath) && nostdlib) { // Add the target assembly to the references list, to allow it to be considered as "mscorlib". // This allows "ikvmstub -nostdlib \...\mscorlib.dll" to work. references.Add(assemblyNameOrPath); } StaticCompiler.Resolver.Warning += new AssemblyResolver.WarningEvent(Resolver_Warning); StaticCompiler.Resolver.Init(StaticCompiler.Universe, nostdlib, references, libpaths); Dictionary <string, Assembly> cache = new Dictionary <string, Assembly>(); foreach (string reference in references) { Assembly[] dummy = null; if (!StaticCompiler.Resolver.ResolveReference(cache, ref dummy, reference)) { Console.Error.WriteLine("Error: reference not found {0}", reference); return(1); } } Assembly assembly = null; try { file = new FileInfo(assemblyNameOrPath); } catch (System.Exception x) { Console.Error.WriteLine("Error: unable to load \"{0}\"\n {1}", assemblyNameOrPath, x.Message); return(1); } if (file != null && file.Exists) { assembly = StaticCompiler.LoadFile(assemblyNameOrPath); } else { assembly = StaticCompiler.Resolver.LoadWithPartialName(assemblyNameOrPath); } int rc = 0; if (assembly == null) { Console.Error.WriteLine("Error: Assembly \"{0}\" not found", assemblyNameOrPath); } else { if (bootstrap) { StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location); ClassLoaderWrapper.SetBootstrapClassLoader(new BootstrapBootstrapClassLoader()); } else { StaticCompiler.LoadFile(typeof(NetExp).Assembly.Location); StaticCompiler.runtimeAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.Runtime.dll")); JVM.CoreAssembly = StaticCompiler.LoadFile(Path.Combine(typeof(NetExp).Assembly.Location, "../IKVM.OpenJDK.Core.dll")); } if (AttributeHelper.IsJavaModule(assembly.ManifestModule)) { Console.Error.WriteLine("Warning: Running ikvmstub on ikvmc compiled assemblies is not supported."); } if (outputFile == null) { outputFile = assembly.GetName().Name + ".jar"; } try { using (zipFile = new ZipOutputStream(new FileStream(outputFile, FileMode.Create))) { zipFile.SetComment(GetVersionAndCopyrightInfo()); try { List <Assembly> assemblies = new List <Assembly>(); assemblies.Add(assembly); if (autoLoadSharedClassLoaderAssemblies) { LoadSharedClassLoaderAssemblies(assembly, assemblies); } foreach (Assembly asm in assemblies) { if (ProcessTypes(asm.GetTypes(), continueOnError) != 0) { rc = 1; if (!continueOnError) { break; } } if (forwarders && ProcessTypes(asm.ManifestModule.__GetExportedTypes(), continueOnError) != 0) { rc = 1; if (!continueOnError) { break; } } } } catch (System.Exception x) { Console.Error.WriteLine(x); if (!continueOnError) { Console.Error.WriteLine("Warning: Assembly reflection encountered an error. Resultant JAR may be incomplete."); } rc = 1; } } } catch (ZipException x) { rc = 1; if (zipCount == 0) { Console.Error.WriteLine("Error: Assembly contains no public IKVM.NET compatible types"); } else { Console.Error.WriteLine("Error: {0}", x.Message); } } } return(rc); }
public MemoryStream ExportApp(bool includeContentGroups = false, bool resetAppGuid = false) { // Get Export XML var attributeSets = App.TemplateManager.GetAvailableContentTypes(true); attributeSets = attributeSets.Where(a => !a.ConfigurationIsOmnipresent); var attributeSetIds = attributeSets.Select(p => p.AttributeSetId.ToString()).ToArray(); var entities = DataSource.GetInitialDataSource(_zoneId, _appId).Out["Default"].List.Where(e => e.Value.AssignmentObjectTypeId != ContentTypeHelpers.AssignmentObjectTypeIDSexyContentTemplate && e.Value.AssignmentObjectTypeId != Constants.AssignmentObjectTypeIdFieldProperties).ToList(); if (!includeContentGroups) { entities = entities.Where(p => p.Value.Type.StaticName != _sexycontentContentgroupName).ToList(); } var entityIds = entities .Select(e => e.Value.EntityId.ToString()).ToArray(); var messages = new List <ExportImportMessage>(); var xmlExport = new XmlExporter(_zoneId, _appId, true, attributeSetIds, entityIds); #region reset App Guid if necessary if (resetAppGuid) { var root = xmlExport.ExportXDocument;//.Root; var appGuid = root.XPathSelectElement("/SexyContent/Header/App").Attribute("Guid"); appGuid.Value = _blankGuid; } #endregion string xml = xmlExport.GenerateNiceXml(); #region Copy needed files to temporary directory var randomShortFolderName = Guid.NewGuid().ToString().Substring(0, 4); var temporaryDirectoryPath = HttpContext.Current.Server.MapPath(Path.Combine(Settings.TemporaryDirectory, randomShortFolderName)); if (!Directory.Exists(temporaryDirectoryPath)) { Directory.CreateDirectory(temporaryDirectoryPath); } AddInstructionsToPackageFolder(temporaryDirectoryPath); var tempDirectory = new DirectoryInfo(temporaryDirectoryPath); var appDirectory = tempDirectory.CreateSubdirectory("Apps/" + App.Folder + "/"); var sexyDirectory = appDirectory.CreateSubdirectory(_zipFolderForAppStuff); var portalFilesDirectory = appDirectory.CreateSubdirectory(_zipFolderForPortalFiles); // Copy app folder if (Directory.Exists(App.PhysicalPath)) { FileManager.CopyAllFiles(sexyDirectory.FullName, false, messages); } // Copy PortalFiles foreach (var file in xmlExport.ReferencedFiles) { var portalFilePath = Path.Combine(portalFilesDirectory.FullName, Path.GetDirectoryName(file.RelativePath.Replace('/', '\\'))); if (!Directory.Exists(portalFilePath)) { Directory.CreateDirectory(portalFilePath); } if (File.Exists(file.PhysicalPath)) { var fullPath = Path.Combine(portalFilesDirectory.FullName, file.RelativePath.Replace('/', '\\')); try { File.Copy(file.PhysicalPath, fullPath); } catch (Exception e) { throw new Exception("Error on " + fullPath + " (" + fullPath.Length + ")", e); } } } // Save export xml File.AppendAllText(Path.Combine(appDirectory.FullName, _AppXmlFileName), xml); #endregion // Zip directory and return as stream var stream = new MemoryStream(); var zipStream = new ZipOutputStream(stream); zipStream.SetLevel(6); ZipFolder(tempDirectory.FullName + "\\", tempDirectory.FullName + "\\", zipStream); zipStream.Finish(); tempDirectory.Delete(true); return(stream); }
/// <summary> /// Entry point /// </summary> internal static int Main(string[] args) { try { #if DEBUG if (args.Length == 0) { var assemblyFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location); var folder = Path.GetFullPath(Path.Combine(assemblyFolder, @"..\..\..\..\Sources\Framework\Generated")); var sdkRoot = Path.GetFullPath(Path.Combine(assemblyFolder, @"..\..\..\..\Binaries")); var xmlFolder = Path.GetFullPath(Path.Combine(assemblyFolder, @"..\..\..\Android\Docs\xml")); var forwardAssembliesFolder = Path.GetFullPath(Path.Combine(assemblyFolder, @"..\..\..\..\Sources\Framework\ForwardAssemblies")); //var sdkRoot = Environment.GetEnvironmentVariable("ANDROID_SDK_ROOT"); if (string.IsNullOrEmpty(sdkRoot)) { throw new ArgumentException("Set ANDROID_SDK_ROOT environment variable"); } var platformFolder = Path.Combine(sdkRoot, @"platforms\android-15"); args = new[] { ToolOptions.InputJar.CreateArg(Path.Combine(platformFolder, "Android.jar")), ToolOptions.InputAttrsXml.CreateArg(Path.Combine(platformFolder, @"data\res\values\attrs.xml")), ToolOptions.InputSourceProperties.CreateArg(Path.Combine(platformFolder, "source.properties")), ToolOptions.OutputFolder.CreateArg(folder), //ToolOptions.DoxygenXmlFolder.CreateArg(xmlFolder), //ToolOptions.PublicKeyToken.CreateArg("0a72796057571e65"), ToolOptions.ForwardAssembliesFolder.CreateArg(forwardAssembliesFolder) }; } #endif var options = new CommandLineOptions(args); if (options.ShowHelp) { options.Usage(); return(2); } if (!File.Exists(options.FrameworkJar)) { throw new ArgumentException(string.Format("Framework jar ({0}) not found.", options.FrameworkJar)); } if (!File.Exists(options.SourceProperties)) { throw new ArgumentException(string.Format("Source.properties ({0}) not found.", options.SourceProperties)); } var sdkPropertiesPath = Path.Combine(Path.GetDirectoryName(options.SourceProperties), "sdk.properties"); if (!File.Exists(sdkPropertiesPath)) { throw new ArgumentException(string.Format("sdk.properties ({0}) not found.", sdkPropertiesPath)); } // Load source.properties var sourceProperties = new SourceProperties(options.SourceProperties); using (var jf = new JarFile(File.Open(options.FrameworkJar, FileMode.Open, FileAccess.Read), AttributeConstants.Dot42Scope, null)) { // Create output folder var folder = Path.Combine(options.OutputFolder, sourceProperties.PlatformVersion); Directory.CreateDirectory(folder); if (!options.VersionOnly) { // Load Doxygen model var xmlModel = new DocModel(); using (Profiler.Profile(x => Console.WriteLine("{0:####} ms for loading Doxygen", x.TotalMilliseconds))) { xmlModel.Load(options.DoxygenXmlFolder); } // Create mscorlib CreateFrameworkAssembly(jf, xmlModel, sourceProperties, folder); // Copy AndroidManifest.xml into the assembly. var manifestStream = jf.GetResource("AndroidManifest.xml"); // Copy resources.arsc into the assembly. var resourcesStream = jf.GetResource("resources.arsc"); // Load attrs.xml into memory var attrsXml = File.ReadAllBytes(options.AttrsXml); // Load layout.xml into memory var layoutXml = File.ReadAllBytes(Path.Combine(folder, "layout.xml")); // Create base package var basePackagePath = Path.Combine(folder, "base.apk"); using (var fileStream = new FileStream(basePackagePath, FileMode.Create, FileAccess.Write)) { using (var zipStream = new ZipOutputStream(fileStream) { UseZip64 = UseZip64.Off }) { #if !DEBUG zipStream.SetLevel(9); #endif zipStream.PutNextEntry(new ZipEntry("AndroidManifest.xml") { CompressionMethod = CompressionMethod.Deflated }); zipStream.Write(manifestStream, 0, manifestStream.Length); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry("resources.arsc") { CompressionMethod = CompressionMethod.Deflated }); zipStream.Write(resourcesStream, 0, resourcesStream.Length); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry(@"attrs.xml") { CompressionMethod = CompressionMethod.Deflated }); zipStream.Write(attrsXml, 0, attrsXml.Length); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry(@"layout.xml") { CompressionMethod = CompressionMethod.Deflated }); zipStream.Write(layoutXml, 0, layoutXml.Length); zipStream.CloseEntry(); } } // Create output folder file if (!string.IsNullOrEmpty(options.OutputFolderFile)) { File.WriteAllText(options.OutputFolderFile, folder); } } // Create output version file var version = string.Format(File.ReadAllText(Path.Combine(folder, "..", "..", "Header.txt")), "Version.cs") + Environment.NewLine + string.Format("[assembly: System.Reflection.AssemblyVersion(\"{0}\")]", sourceProperties.AssemblyVersion) + Environment.NewLine + string.Format("[assembly: System.Reflection.AssemblyFileVersion(\"{0}\")]", sourceProperties.AssemblyFileVersion) + Environment.NewLine + string.Format("[assembly: System.Reflection.AssemblyInformationalVersion(\"{0}\")]", sourceProperties.AssemblyInformationalVersion) + Environment.NewLine + "#if !BASELIB" + Environment.NewLine + string.Format("[assembly: System.Runtime.Versioning.TargetFramework(\"Dot42,Version={0}\", FrameworkDisplayName = \"Dot42\")]", sourceProperties.PlatformVersion) + Environment.NewLine + "#endif" + Environment.NewLine; File.WriteAllText(Path.Combine(folder, "Version.cs"), version); if (!options.VersionOnly) { // Load sdk.properties var sdkProperties = new SdkProperties(sdkPropertiesPath); // Create framework ini var frameworkIni = new FrameworkIni(folder); Initialize(frameworkIni, sourceProperties, sdkProperties); frameworkIni.Save(); // Create FrameworkList.xml FrameworkListBuilder.Build(folder, options.ForwardAssembliesFolder, options.PublicKeyToken, sourceProperties.AssemblyVersion, sourceProperties.PlatformVersion); } } return(0); } catch (Exception ex) { Console.WriteLine(ex.Message); #if DEBUG Console.WriteLine(ex.StackTrace); #endif return(1); } }
public static MemberListSyncResult GetMemberListSync(string updatedOn, string grpID, out string filepath) { bool isDataFound = false; string targetPath = ""; try { filepath = ""; MySqlParameter[] param = new MySqlParameter[2]; param[0] = new MySqlParameter("@groupID", grpID); param[1] = new MySqlParameter("@updatedOn", updatedOn); DataSet result = MySqlHelper.ExecuteDataset(GlobalVar.strAppConn, CommandType.StoredProcedure, "V7_USPGetDirectoryListSync", param); DataTable dtnewMember = result.Tables[0]; DataTable dtUpdatedMember = result.Tables[1]; DataTable dtDeletedMember = result.Tables[2]; int dataCount = 10;// Used for paging. DataCount is page size List <MemberDetailsDynamicField> memberList; int Filecounter = 1; int totalrows = dtnewMember.Rows.Count; string FileName = "Dist-" + grpID + DateTime.Now.ToString("ddMMyyyyhhmmsstt"); MemberListSyncResult memListSyncResult = new MemberListSyncResult(); //======================= If total records less than 20 Return Json directly ================================================= int totalRowCount; if (Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") == "01/01/1970") { totalRowCount = dtnewMember.Rows.Count; } else { totalRowCount = dtnewMember.Rows.Count + dtUpdatedMember.Rows.Count; } if (totalRowCount <= 20) { //---------------Create array of new members ------------------------------- memberList = new List <MemberDetailsDynamicField>(); if (dtnewMember.Rows.Count > 0) { for (int i = 0; i < dtnewMember.Rows.Count; i++) { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtnewMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); } } memListSyncResult.NewMemberList = memberList; //---------------Create array of Updated members ------------------------------- memberList = new List <MemberDetailsDynamicField>(); if (dtUpdatedMember.Rows.Count > 0 && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { for (int i = 0; i < dtUpdatedMember.Rows.Count; i++) { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtUpdatedMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); } } memListSyncResult.UpdatedMemberList = memberList; //-----------------Deleted member -------------------------------------------------- string deletedProfiles = ""; if (dtDeletedMember != null && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { if (!string.IsNullOrEmpty(dtDeletedMember.Rows[0]["profileID"].ToString())) { deletedProfiles = dtDeletedMember.Rows[0]["profileID"].ToString(); } } memListSyncResult.DeletedMemberList = deletedProfiles; } //======================= If Records Greater than 20 Return Zip File ================================================= else { if (dtnewMember.Rows.Count > 0) { memberList = new List <MemberDetailsDynamicField>(); for (int i = 0; i < totalrows; i++) { if (i < dataCount) // add object to page { try { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtnewMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); MemberDetails memberDtl = new MemberDetails(); memberDtl.MemberDetail = memberList; // For each page create a seperate json file if (i == dataCount - 1 || i == totalrows - 1) { // create a file string json = JsonConvert.SerializeObject(memberDtl); //write string to file string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/NewMembers")) { Directory.CreateDirectory(Path + "/NewMembers"); } System.IO.File.WriteAllText(Path + "/NewMembers/New" + Filecounter + ".json", json); Filecounter++; } } catch { } } else { // reset member list for next page memberList = new List <MemberDetailsDynamicField>(); dataCount = dataCount + 10; i--; } } } if (dtUpdatedMember.Rows.Count > 0 && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { dataCount = 10; // Used for paging. dataCount is page size memberList = new List <MemberDetailsDynamicField>(); Filecounter = 1; totalrows = dtUpdatedMember.Rows.Count; for (int i = 0; i < totalrows; i++) { if (i < dataCount) { try { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtUpdatedMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); MemberDetails memberDtl = new MemberDetails(); memberDtl.MemberDetail = memberList; // For each page create a seperate json file if (i == dataCount - 1 || i == totalrows - 1) { // create a file string json = JsonConvert.SerializeObject(memberDtl); //write string to file string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/UpdatedMembers")) { Directory.CreateDirectory(Path + "/UpdatedMembers"); } System.IO.File.WriteAllText(Path + "/UpdatedMembers/Update" + Filecounter + ".json", json); Filecounter++; } } catch { } } else { // reset member list for next page memberList = new List <MemberDetailsDynamicField>(); dataCount = dataCount + 10; i--; } } } if (dtDeletedMember != null && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { if (!string.IsNullOrEmpty(dtDeletedMember.Rows[0]["profileID"].ToString())) { string deletedProfiles = dtDeletedMember.Rows[0]["profileID"].ToString(); string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/DeletedMembers")) { Directory.CreateDirectory(Path + "/DeletedMembers"); } System.IO.File.WriteAllText(Path + "/DeletedMembers/Delete" + Filecounter + ".txt", deletedProfiles); } } string zipFolderPath = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (Directory.Exists(zipFolderPath)) { targetPath = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName + ".zip"; zos = new ZipOutputStream(File.Create(targetPath)); zos.UseZip64 = UseZip64.Off; strBaseDir = zipFolderPath + "\\"; AddZipEntry(strBaseDir); zos.Finish(); zos.Close(); isDataFound = true; } if (isDataFound) { filepath = ConfigurationManager.AppSettings["imgPath"] + "TempDocuments/DirectoryData/Profile" + FileName + ".zip"; } } return(memListSyncResult); } catch { throw; } }
public static void ZipFileDirectory(string strDirectory, string zipedFile) { using (FileStream stream = File.Create(zipedFile)) { using (ZipOutputStream stream2 = new ZipOutputStream(stream)) { ZipSetp(strDirectory, stream2, ""); } } }
public static void ZipFile(string fileToZip, string zipedFile) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.OpenRead(fileToZip)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); using (FileStream stream2 = File.Create(zipedFile)) { using (ZipOutputStream stream3 = new ZipOutputStream(stream2)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream3.PutNextEntry(entry); stream3.SetLevel(5); stream3.Write(buffer, 0, buffer.Length); stream3.Finish(); stream3.Close(); } } } }
static void AddToZip(ZipOutputStream zip, string filename, byte[] data) { AddToZip(zip, filename, data, data.Length); }
public static void CreateZip(string[] filesToZip, string destDir, string zipFileName) { try { string stZipPath = destDir + zipFileName; // TextLogger2.Log("Starting compression..." ); //ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) { //FileInfo ff = new System.IO.FileInfo(stZipPath); //File.SetAttributes(stZipPath, FileAttributes.Normal); File.Delete(stZipPath); } Crc32 crc = new Crc32(); using (FileStream fs1 = new FileStream(stZipPath, FileMode.Create,FileAccess.ReadWrite,FileShare.Delete)) { using (ZipOutputStream zipOutput = new ZipOutputStream(fs1)) { zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression // TextLogger2.Log(filesToZip.Length + " file(s) to zip."); int index = 0; foreach (string file in filesToZip) { FileInfo fi = new System.IO.FileInfo(file); ZipEntry entry = new ZipEntry(fi.Name); using (FileStream fs = File.OpenRead(fi.FullName)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive //string stFileName = fi.FullName.Remove(0, destDir.Length + 1); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } } } } //zipOutput.Finish(); //zipOutput.Close(); //fs1.Flush(); //fs1.Close(); //Force clean up GC.Collect(); //zipOutput = null; //TextLogger2.Log("Compression Successful."); } catch (Exception ex) { throw ex; } }
static void AddToZip(ZipOutputStream zip, string filename, byte[] data, int length) { CreateZipEntry(zip, filename); zip.Write(data, 0, length); }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="isImage">Indicates whether the file specified in <paramref name="filePath"/> is an image. If it /// is, and <paramref name="applyWatermark"/> is <c>true</c>, a watermark is applied to the image as it is inserted /// into the archive.</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// This parameter is ignored when <paramref name="isImage"/> is <c>false</c>. When this parameter is <c>true</c>, the /// <paramref name="galleryId" /> must be specified.</param> /// <param name="galleryId">The ID for the gallery associated with the <paramref name="filePath" />. Since each gallery can /// have its own watermark, this value is used to ensure the correct watermark is used. This parameter is ignored when /// <paramref name="isImage" /> or <paramref name="applyWatermark" /> is <c>false</c>.</param> /// <exception cref="ArgumentException">Thrown when <paramref name="isImage" /> is <c>true</c>, <paramref name="applyWatermark" /> /// is <c>true</c> and the <paramref name="galleryId" /> is <see cref="Int32.MinValue" />.</exception> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath, bool isImage, bool applyWatermark, int galleryId) { if (isImage && applyWatermark && (galleryId == int.MinValue)) { throw new ArgumentException("You must specify a gallery ID when the isImage and applyWatermark parameters are set to true."); } int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; #region Determine ZIP entry name // Get name of the file as it will be stored in the ZIP archive. This is the fragment of the full file path // after the base path. Ex: If basePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\" // and filePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg", // then zipEntryName="desert sunsets\zOpt_sonorandesert.jpg". The ZIP algorithm will automatically sense the // embedded directory ("desert sunsets") and create it. string zipEntryName; if (String.IsNullOrEmpty(fileNameForZip)) { zipEntryName = filePath.Replace(basePath, String.Empty); } else { zipEntryName = fileNameForZip.Replace(basePath, String.Empty); } #endregion using (Stream stream = CreateStream(filePath, isImage, applyWatermark, galleryId)) { ZipEntry entry = new ZipEntry(zipEntryName); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
static void CreateArchive() { try { using (ZipOutputStream zip = new ZipOutputStream(File.Create(zipFile))) { zip.SetComment("Created by Goblin Camp crash reporter service."); zip.SetLevel(6); AddToZip(zip, dumpFile); AddToZip(zip, "config.py", "..\\config.py"); AddToZip(zip, "terminal.png", "..\\terminal.png"); AddToZip(zip, "goblin-camp.log", "..\\goblin-camp.log"); DirectoryInfo modsDir = new DirectoryInfo(dataDir + "mods"); StringBuilder modsList = new StringBuilder(1024); modsList.Append("=========[ Installed mods ]=========\n"); foreach (DirectoryInfo subdir in modsDir.GetDirectories()) { modsList.AppendFormat(" * {0}\n", subdir.Name); if (File.Exists(subdir.FullName + "\\mod.dat")) { AddToZip(zip, "mods\\" + subdir.Name + ".dat", subdir.FullName + "\\mod.dat"); } } UTF8Encoding utf8 = new UTF8Encoding(); AddToZip(zip, "mods.txt", utf8.GetBytes(modsList.ToString())); StringBuilder wmiCollectedData = new StringBuilder(8192); // We are querying local WMI to get following data: // - video cards, along with drivers' info wmiCollectedData.Append("=========[ Installed video controllers ]=========\n"); foreach (ManagementObject obj in QueryWMI("SELECT * FROM Win32_VideoController")) { wmiCollectedData.AppendFormat(" * {0} [{1}]\n", GetWMIProperty(obj, "Description"), GetWMIProperty(obj, "VideoProcessor")); wmiCollectedData.AppendFormat(" VRAM: {0}MB\n", GetWMIIntProperty(obj, "AdapterRAM") / (1024 * 1024)); wmiCollectedData.AppendFormat(" BPP: {0}\n", GetWMIProperty(obj, "CurrentBitsPerPixel")); wmiCollectedData.AppendFormat( " Driver: {0} ({1})\n", GetWMIProperty(obj, "DriverVersion"), GetWMIProperty(obj, "DriverDate") ); foreach (string driver in GetWMIProperty(obj, "InstalledDisplayDrivers").ToString().Split(',')) { wmiCollectedData.AppendFormat(" {0}\n", driver); } wmiCollectedData.AppendFormat(" Current video mode: {0}\n", GetWMIProperty(obj, "VideoModeDescription")); } // - attached monitors wmiCollectedData.Append("\n=========[ Attached monitors ]=========\n"); foreach (ManagementObject obj in QueryWMI("SELECT * FROM Win32_DesktopMonitor")) { wmiCollectedData.AppendFormat(" * {0}\n", GetWMIProperty(obj, "Description")); wmiCollectedData.AppendFormat( " Resolution: {0} x {1}\n", GetWMIProperty(obj, "ScreenWidth"), GetWMIProperty(obj, "ScreenHeight") ); } // - operating system info wmiCollectedData.Append("\n=========[ Operating system ]=========\n"); foreach (ManagementObject obj in QueryWMI("SELECT * FROM Win32_OperatingSystem WHERE Primary = TRUE")) { wmiCollectedData.AppendFormat("{0}\n", GetWMIProperty(obj, "Caption")); wmiCollectedData.AppendFormat( "Physical memory (free/total): {0}MB / {1}MB\n", GetWMIIntProperty(obj, "FreePhysicalMemory") / 1024, GetWMIIntProperty(obj, "TotalVisibleMemorySize") / 1024 ); wmiCollectedData.AppendFormat("Architecture: {0}\n", GetWMIProperty(obj, "OSArchitecture")); break; // I'm lazy } AddToZip(zip, "wmi.txt", utf8.GetBytes(wmiCollectedData.ToString())); } } catch (Exception e) { MessageBox.Show( e.ToString(), "Error while creating the archive.", MessageBoxButtons.OK, MessageBoxIcon.Error ); } form.Invoke(new UIUpdateDelegate(form.ArchiveReady)); }
void NewCreateZip(SPListItem item, ZipOutputStream zs) { SPSecurity.RunWithElevatedPrivileges(delegate { if (null != item.Folder) { foreach (SPFile file in item.Folder.Files) { NewCreateZip(file.Item, zs); } foreach (SPFolder folder in item.Folder.SubFolders) { NewCreateZip(folder.Item, zs); } } else { ZipEntry entry = new ZipEntry(item.File.Url.Substring(iParentFolderLength)); zs.PutNextEntry(entry); int intReadLength = 0; Stream s = item.File.OpenBinaryStream(); do { byte[] buffer = new byte[1024]; intReadLength = s.Read(buffer, 0, buffer.Length); zs.Write(buffer, 0, intReadLength); } while (intReadLength == 1024); s.Dispose(); s.Close(); } }); }
protected bool PackageFiles() { var flag = false; var crc = new Crc32(); ZipOutputStream stream = null; try { using (stream = new ZipOutputStream(File.Create(PackageFileName))) { stream.SetLevel(9); var buffer = new byte[0x8000]; foreach (var item in Files) { var itemSpec = item.ItemSpec; var info = new FileInfo(itemSpec); if (!info.Exists) { Log.LogWarning("File not found", new object[] { info.FullName }); } else { itemSpec = ZipEntry.CleanName(info.Name, true); var entry = new ZipEntry(itemSpec); entry.DateTime = info.LastWriteTime; entry.Size = info.Length; using (var stream2 = info.OpenRead()) { crc.Reset(); var length = stream2.Length; while (length > 0L) { var len = stream2.Read(buffer, 0, buffer.Length); crc.Update(buffer, 0, len); length -= len; } entry.Crc = crc.Value; stream.PutNextEntry(entry); length = stream2.Length; stream2.Seek(0L, SeekOrigin.Begin); while (length > 0L) { var count = stream2.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, count); length -= count; } } Log.LogMessage("File added to package", new object[] { itemSpec }); } } stream.Finish(); } Log.LogMessage("Package created", new object[] { PackageFileName }); flag = true; } catch (Exception exception) { Log.LogErrorFromException(exception); flag = false; } finally { if (stream != null) { stream.Close(); } } return(flag); }
public ZipContainer(Object o) { _zf = (o as ZipFile); _zos = (o as ZipOutputStream); _zis = (o as ZipInputStream); }
public override TaskStatus Run() { Info("Zipping files..."); bool success = true; var files = SelectFiles(); if (files.Length > 0) { if (string.IsNullOrEmpty(ZipFileName)) { var fileName = Path.GetFileNameWithoutExtension(files[0].RenameToOrName); ZipFileName = fileName + ".zip"; } var zipPath = Path.Combine(Workflow.WorkflowTempFolder, ZipFileName); try { using (var s = new ZipOutputStream(File.Create(zipPath))) { s.SetLevel(9); // 0 - store only to 9 - means best compression var buffer = new byte[4096]; foreach (FileInf file in files) { // Using GetFileName makes the result compatible with XP // as the resulting path is not absolute. var entry = new ZipEntry(Path.GetFileName(file.Path)) { DateTime = DateTime.Now }; // Setup the entry data as required. // Crc and size are handled by the library for seakable streams // so no need to do them here. // Could also use the last write time or similar for the file. s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file.Path)) { // Using a fixed size buffer here makes no noticeable difference for output // but keeps a lid on memory usage. int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // Finish/Close arent needed strictly as the using statement does this automatically // Finish is important to ensure trailing information for a Zip file is appended. Without this // the created file would be invalid. s.Finish(); // Close is important to wrap things up and unlock the file. s.Close(); InfoFormat("Zip {0} created.", zipPath); Files.Add(new FileInf(zipPath, Id)); } } catch (ThreadAbortException) { throw; } catch (Exception e) { ErrorFormat("An error occured while creating the Zip {0}", e, zipPath); success = false; } } var status = Status.Success; if (!success) { status = Status.Error; } Info("Task finished."); return(new TaskStatus(status, false)); }
/// <summary> /// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="filePath"/>. /// The archive is created in memory and is not stored on disk. If filePath is an image, no attempt is made to apply a /// watermark, even if watermarking is enabled. /// </summary> /// <param name="filePath">The full path to a file to be added to a ZIP archive.</param> /// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified file.</returns> public Stream CreateZipStream(string filePath) { MemoryStream ms = new MemoryStream(); ZipOutputStream zos = new ZipOutputStream(ms); zos.SetLevel(ZIP_COMPRESSION_LEVEL); AddFileZipEntry(zos, filePath, null, Path.GetDirectoryName(filePath), false, false); zos.Finish(); return ms; }
static int Main(string[] args) { Console.OutputEncoding = Encoding.Unicode; TextWriter outTextWriter = args.Length >= 0 ? Console.Out : null; if (args.Length < 1) { outTextWriter?.WriteLine("No input directory specified"); return(1); } if (args.Length < 2) { outTextWriter?.WriteLine("No merge directory specified"); return(1); } if (args.Length < 3) { outTextWriter?.WriteLine("No output directory specified"); return(1); } string inFileName = args[0]; if (string.IsNullOrEmpty(inFileName)) { outTextWriter?.WriteLine("Input file empty"); return(1); } string mergeFileName = args[1]; if (string.IsNullOrEmpty(mergeFileName)) { outTextWriter?.WriteLine("Merge file empty"); return(1); } string outFile = args[2]; if (string.IsNullOrEmpty(outFile)) { outTextWriter?.WriteLine("Output file empty"); return(1); } try { if (!File.Exists(inFileName)) { outTextWriter?.WriteLine("Input file not existing"); return(1); } if (!File.Exists(mergeFileName)) { outTextWriter?.WriteLine("Merge file not existing"); return(1); } List <string> entryList = GetZipEntryList(inFileName); if (entryList == null || entryList.Count == 0) { outTextWriter?.WriteLine("No entries in zip found"); return(1); } FileStream fsOut = null; ZipOutputStream zipStream = null; try { fsOut = File.Create(outFile); zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression foreach (string entryName in entryList) { try { bool stored = false; if (!entryName.StartsWith("faultdata_", StringComparison.OrdinalIgnoreCase)) { if (GetEcuDataObject(inFileName, entryName, typeof(EcuFunctionStructs.EcuVariant)) is EcuFunctionStructs.EcuVariant ecuVariantIn) { if (GetEcuDataObject(mergeFileName, entryName, typeof(EcuFunctionStructs.EcuVariant)) is EcuFunctionStructs.EcuVariant ecuVariantMerge) { MergeEcuVariant(outTextWriter, entryName, ecuVariantIn, ecuVariantMerge); XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" }; XmlSerializer serializer = new XmlSerializer(typeof(EcuFunctionStructs.EcuVariant)); using (MemoryStream memStream = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(memStream, settings)) { serializer.Serialize(writer, ecuVariantIn); } AddZipEntry(zipStream, entryName, memStream); } stored = true; } } } if (!stored) { using (MemoryStream memStream = new MemoryStream()) { if (GetZipDataStream(inFileName, entryName, memStream)) { AddZipEntry(zipStream, entryName, memStream); } else { throw new Exception(string.Format("Copy zip entry {0} failed", entryName)); } } } } catch (Exception e) { outTextWriter?.WriteLine(e); } } } finally { if (zipStream != null) { zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); } fsOut?.Close(); } } catch (Exception e) { outTextWriter?.WriteLine(e); } return(0); }
private void SaveSharedStringHandler(ZipOutputStream stream, CompressionLevel compressionLevel, string fileName) { //Packaging.ZipPackagePart stringPart; //if (_package.Package.PartExists(SharedStringsUri)) //{ // stringPart=_package.Package.GetPart(SharedStringsUri); //} //else //{ // stringPart = _package.Package.CreatePart(SharedStringsUri, @"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", _package.Compression); //Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); //} //StreamWriter sw = new StreamWriter(stringPart.GetStream(FileMode.Create, FileAccess.Write)); //Init Zip stream.CompressionLevel = (OfficeOpenXml.Packaging.Ionic.Zlib.CompressionLevel)compressionLevel; stream.PutNextEntry(fileName); var cache = new StringBuilder(); var sw = new StreamWriter(stream); cache.AppendFormat("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"{0}\" uniqueCount=\"{0}\">", _sharedStrings.Count); foreach (string t in _sharedStrings.Keys) { SharedStringItem ssi = _sharedStrings[t]; if (ssi.isRichText) { cache.Append("<si>"); ConvertUtil.ExcelEncodeString(cache, t); cache.Append("</si>"); } else { if (t.Length>0 && (t[0] == ' ' || t[t.Length-1] == ' ' || t.Contains(" ") || t.Contains("\t"))) { cache.Append("<si><t xml:space=\"preserve\">"); } else { cache.Append("<si><t>"); } ConvertUtil.ExcelEncodeString(cache, ConvertUtil.ExcelEscapeString(t)); cache.Append("</t></si>"); } if (cache.Length > 0x600000) { sw.Write(cache.ToString()); cache = new StringBuilder(); } } cache.Append("</sst>"); sw.Write(cache.ToString()); sw.Flush(); Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); }
void zip() { System.Uri dest = new System.Uri(uri_chooser.Uri); Crc32 crc = new Crc32(); string filedest = dest.LocalPath + "/" + filename.Text; Log.DebugFormat("Creating zip file {0}", filedest); ZipOutputStream s = new ZipOutputStream(File.Create(filedest)); if (scale_check.Active) { Log.DebugFormat("Scaling to {0}", scale_size.ValueAsInt); } ProgressDialog progress_dialog = new ProgressDialog(Catalog.GetString("Exporting files"), ProgressDialog.CancelButtonType.Stop, photos.Length, zipdiag); //Pack up for (int i = 0; i < photos.Length; i++) { if (progress_dialog.Update(String.Format(Catalog.GetString("Preparing photo \"{0}\""), photos[i].Name))) { progress_dialog.Destroy(); return; } string f = null; // FIXME: embed in a try/catch if (scale_check.Active) { FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter((uint)scale_size.ValueAsInt)); FilterRequest freq = new FilterRequest(photos [i].DefaultVersion.Uri); filters.Convert(freq); f = freq.Current.LocalPath; } else { f = photos [i].DefaultVersion.Uri.LocalPath; } FileStream fs = File.OpenRead(f); byte [] buffer = new byte [fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(photos [i].DefaultVersion.Uri.LocalPath)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); if (progress_dialog != null) { progress_dialog.Destroy(); } }
public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.Create(zipedFile)) { using (ZipOutputStream stream2 = new ZipOutputStream(stream)) { using (FileStream stream3 = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream2.PutNextEntry(entry); stream2.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int count = 0; try { do { count = stream3.Read(buffer, 0, buffer.Length); stream2.Write(buffer, 0, count); } while (count > 0); } catch (Exception exception) { throw exception; } stream3.Close(); } stream2.Finish(); stream2.Close(); } stream.Close(); } }
//using ICSharpCode.SharpZipLib.Zip; #region 加压解压方法 /// <summary> /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略) /// </summary> /// <param name="dirPath">被压缩的文件夹夹路径</param> /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param> /// <param name="err">出错信息</param> /// <returns>是否压缩成功</returns> public bool ZipFile(string dirPath, List <string> filenames, string zipFilePath, out string err) { err = ""; #region //if (dirPath == string.Empty) //{ // err = "要压缩的文件夹不能为空!"; // return false; //} //if (!Directory.Exists(dirPath)) //{ // err = "要压缩的文件夹不存在!"; // return false; //} //压缩文件名为空时使用文件夹名+.zip //if (zipFilePath == string.Empty) //{ // if (dirPath.EndsWith("//")) // { // dirPath = dirPath.Substring(0, dirPath.Length - 1); // } // zipFilePath = dirPath + ".zip"; //} #endregion try { //string[] filenames = Directory.GetFiles(dirPath); using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string file1 in filenames) { var file = dirPath + file1; //判断文件是否存在 if (!File.Exists(file)) { continue; } ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } s.Finish(); s.Close(); } } catch (Exception ex) { err = ex.Message; return(false); } return(true); }
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory = strDirectory + Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); string[] fileSystemEntries = Directory.GetFileSystemEntries(strDirectory); foreach (string str in fileSystemEntries) { if (Directory.Exists(str)) { string str2 = parentPath; str2 = str2 + str.Substring(str.LastIndexOf(@"\") + 1) + @"\"; ZipSetp(str, s, str2); } else { using (FileStream stream = File.OpenRead(str)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(parentPath + str.Substring(str.LastIndexOf(@"\") + 1)) { DateTime = DateTime.Now, Size = stream.Length }; stream.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } }
/// <summary> /// 递归压缩文件夹的内部方法 /// </summary> /// <param name="folderToZip">要压缩的文件夹路径</param> /// <param name="zipStream">压缩输出流</param> /// <param name="parentFolderName">此文件夹的上级文件夹</param> /// <returns></returns> private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName) { bool result = true; string[] folders, files; ZipEntry ent = null; FileStream fs = null; Crc32 crc = new Crc32(); try { ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); zipStream.PutNextEntry(ent); zipStream.Flush(); files = Directory.GetFiles(folderToZip); foreach (string file in files) { fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file))); ent.DateTime = DateTime.Now; ent.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); ent.Crc = crc.Value; zipStream.PutNextEntry(ent); zipStream.Write(buffer, 0, buffer.Length); } } catch { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { if (!ZipDirectory(folder, zipStream, folderToZip)) { return(false); } } return(result); }
public static void TestZippedStream(int len, int ziplevel) { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(len); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmlteststream01.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(ziplevel); XmlStreamSerializationInfo info = new XmlStreamSerializationInfo(); t1 = DateTime.Now; info.BeginWriting(ZipStream); info.AddValue("FooNode",o); info.EndWriting(); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmlteststream01.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlStreamDeserializationInfo info3 = new XmlStreamDeserializationInfo(); info3.BeginReading(zipinpstream); Foo o3 = (Foo)info3.GetValue(null); info3.EndReading(); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); o3.EnsureEquality(len); }
public void make() { if (_files.Count == 0) { _log.Info("Files == 0"); MessageBox.Show("Files is none", "Premaker", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); return; } if (!Directory.Exists(DescriptionDirectory)) { Directory.CreateDirectory(DescriptionDirectory); } FileInfo listZIP = new FileInfo(DescriptionDirectory + "/list.zip"); ZipOutputStream zipListStream = new ZipOutputStream(listZIP.Create()); zipListStream.SetLevel(COMPRESS_LEVEL); //уровень компресии zipListStream.Password = PASSWORD; //пароль ZipEntry listEntry = new ZipEntry("list.lst"); listEntry.DateTime = DateTime.Now; zipListStream.PutNextEntry(listEntry); writeString(zipListStream, "#Revision:" + REVISION + "\n"); //пишем номер ревизии ChooseForm.Instance.FormAsGameFiles.onStart(); //прогресс бар включаем ChooseForm.Instance.FormAsGameFiles.disableItems(false); //отключаем что б не изменилось for (int i = 0; i < Items.Count; i++) //листаем { if (Break) { ChooseForm.Instance.FormAsGameFiles.setStatus("Break"); ChooseForm.Instance.FormAsGameFiles.setValue(0); return; } lock (zipListStream) { ListFile item = Items[i]; try { if (!item.Exists()) { _log.Info("WTF source file is deleted ??. File: " + item.SourceDirectoryName + item.FileName); continue; } if (item.FileType != ListFileType.DELETE) { item.validateDirectoryes(); FileStream sourceStream = item.CreateSource(); FileStream descriptionStream = item.CreateDescription(); if (sourceStream == null || descriptionStream == null) { _log.Info("WTF streams NULL???. File: " + item.FileName); } ChooseForm.Instance.FormAsGameFiles.setStatus("Compressing " + item.FileName); ZipOutputStream zipDescriptionStream = new ZipOutputStream(descriptionStream); //открываем стрим zipDescriptionStream.SetLevel(COMPRESS_LEVEL); zipDescriptionStream.Password = PASSWORD; ZipEntry entry = new ZipEntry(item.EntryName.Replace(".zip", "")); entry.DateTime = item.SourceTime(); zipDescriptionStream.PutNextEntry(entry); byte[] bytes = new byte[sourceStream.Length]; int readLen = sourceStream.Read(bytes, 0, bytes.Length); sourceStream.Close(); if (readLen != bytes.Length) { _log.Info("WTF source file is not compled read??. File: " + item.FileName); continue; } zipDescriptionStream.Write(bytes, 0, readLen); zipDescriptionStream.Finish(); zipDescriptionStream.Close(); } writeString(zipListStream, item.FileName + "\t" + item.FileType + "\t" + item.MD5 + "\n"); } catch (Exception e) { _log.Info("Exception: file - " + item.FileName, e); } finally { int p = ((100 * i) / Items.Count); if (p > 100) { p = 100; } ChooseForm.Instance.FormAsGameFiles.setValue(p); } } } zipListStream.Finish(); zipListStream.Close(); ChooseForm.Instance.FormAsGameFiles.setStatus("Done"); ChooseForm.Instance.FormAsGameFiles.disableItems(true); ChooseForm.Instance.FormAsGameFiles.onEnd(); }
public static void TestBinarySerializationZipped(int len) { DateTime t1; TimeSpan dt; double[] arr = new double[len]; for(int i=0;i<arr.Length;i++) { arr[i] = Math.PI*Math.Sqrt(i); } // FileStream fs = new FileStream(@"C:\TEMP\testbinformat.bin", FileMode.Create); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip"); ZipOutputStream fs = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); fs.PutNextEntry(ZipEntry); fs.SetLevel(0); // Construct a BinaryFormatter and use it to serialize the data to the stream. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new BinaryFormatter(); t1 = DateTime.Now; try { formatter.Serialize(fs, arr); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Flush(); fs.Close(); } dt = DateTime.Now - t1; Console.WriteLine("Duration: {0}",dt); }
private void StartWork(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(state => { void Advance(string s) { Invoke((Action)(() => AdvanceStep(s))); } void CloseWnd() { Invoke((Action)Close); } var files = manifest.AssetMappings.Select(m => m.Path).Distinct().ToList(); Invoke((Action)(() => { progressBar.Maximum = files.Count + 3; progressLabel.Text = "Preparing"; })); foreach (var file in files) { var fullFile = Path.Combine(baseDir, file); if (File.Exists(fullFile)) { continue; } MessageBox.Show($"Failed to find file {fullFile}, cannot pack!", "Heck", MessageBoxButtons.OK, MessageBoxIcon.Error); CloseWnd(); return; } var zipName = Path.GetFileName(targetPath); Advance($"Packing into {zipName}"); using (var zipStream = new ZipOutputStream(File.Create(targetPath))) { foreach (var file in files) { Advance($"Packing {file}"); zipStream.PutNextEntry(new ZipEntry(file.Replace("\\", "/"))); using var fileStream = File.OpenRead(Path.Combine(baseDir, file)); fileStream.CopyTo(zipStream); } Advance("Packing manifest file"); zipStream.PutNextEntry(new ZipEntry(ModManifest.MANIFEST_FILE_NAME)); using var manifestStream = File.OpenRead(Path.Combine(baseDir, ModManifest.MANIFEST_FILE_NAME)); manifestStream.CopyTo(zipStream); } Advance("Done"); Invoke((Action)(() => { closButton.Enabled = true; openFolderButton.Enabled = true; })); }); }
/// <summary> /// Main method /// </summary> /// <param name="stZipPath">path of the archive wanted</param> /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param> public static void CreateZip(string stZipPath, string stDirToZip) { try { //Sanitize inputs stDirToZip = Path.GetFullPath(stDirToZip); stZipPath = Path.GetFullPath(stZipPath); TextLogger2.Log("Zip directory " + stDirToZip); //Recursively parse the directory to zip Stack<FileInfo> stackFiles = DirExplore(stDirToZip); ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) File.Delete(stZipPath); Crc32 crc = new Crc32(); zipOutput = new ZipOutputStream(File.Create(stZipPath)); zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression TextLogger2.Log(stackFiles.Count + " files to zip.\n"); int index = 0; foreach (FileInfo fi in stackFiles) { ++index; //int percent = (int)((float)index / ((float)stackFiles.Count / 100)); //if (percent % 1 == 0) //{ // Console.CursorLeft = 0; // Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done."); //} FileStream fs = File.OpenRead(fi.FullName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1); ZipEntry entry = new ZipEntry(stFileName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } zipOutput.Finish(); zipOutput.Close(); zipOutput = null; } catch (Exception) { throw; } }
///<summary> ///压缩文件 和 文件夹,不压缩顶级目录 ///</summary> ///<param name="FolderToZip">待压缩的文件夹,全路径格式</param> ///<param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param> ///<returns>压缩是否成功</returns> public static bool ZipNo(string FolderToZip, string ZipedFile) { if (!Directory.Exists(FolderToZip)) { return(false); } if (ZipedFile == string.Empty) { //如果为空则文件名为待压缩的文件名加上.rar ZipedFile = FolderToZip + ".zip"; } ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile)); s.SetLevel(6); string[] filenames = Directory.GetFiles(FolderToZip); ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); foreach (string file in filenames) { //压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[avg]; entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); for (int i = 0; i < fs.Length; i += avg) { if (i + avg > fs.Length) { //不足100MB的部分写剩余部分 buffer = new byte[fs.Length - i]; } fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, buffer.Length); } } if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); //压缩目录 string[] folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, "")) { } } s.Finish(); s.Close(); return(true); }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath) { AddFileZipEntry(zos, filePath, fileNameForZip, basePath, false, false, int.MinValue); }
///<summary> ///压缩文件 ///</summary> ///<param name="FileToZip">要进行压缩的文件名</param> ///<param name="ZipedFile">压缩后生成的压缩文件名,如果为空则文件名为待压缩的文件名加上.rar</param> ///<returns>压缩是否成功</returns> private static bool ZipFile(string FileToZip, string ZipedFile, string Password) { //如果文件没有找到,则报错 if (!File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!"); } if (ZipedFile == string.Empty) { //如果为空则文件名为待压缩的文件名加上.rar ZipedFile = FileToZip + ".zip"; } FileStream ZipFile = null; ZipOutputStream ZipStream = null; ZipEntry ZipEntry = null; bool res = true; ZipFile = File.Create(ZipedFile); ZipStream = new ZipOutputStream(ZipFile); ZipEntry = new ZipEntry(Path.GetFileName(FileToZip)); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(6); if (!string.IsNullOrEmpty(Password.Trim())) { ZipStream.Password = Password.Trim(); } try { ZipFile = File.OpenRead(FileToZip); byte[] buffer = new byte[avg]; for (int i = 0; i < ZipFile.Length; i += avg) { if (i + avg > ZipFile.Length) { //不足100MB的部分写剩余部分 buffer = new byte[ZipFile.Length - i]; } ZipFile.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, buffer.Length); } } catch (Exception ex) { res = false; } finally { if (ZipEntry != null) { ZipEntry = null; } if (ZipStream != null) { ZipStream.Finish(); ZipStream.Close(); } if (ZipFile != null) { ZipFile.Close(); ZipFile = null; } GC.Collect(); GC.Collect(1); } return(res); }
/// <summary> /// Adds the specified <paramref name="content" /> to the ZIP archive, giving it the specified <paramref name="fileNameForZip" />. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the <paramref name="content" /> is to be added to.</param> /// <param name="content">The text to be added to the ZIP archive.</param> /// <param name="fileNameForZip">The name to be given to the <paramref name="content" /> within the ZIP archive.</param> private static void AddFileZipEntry(ZipOutputStream zos, string content, string fileNameForZip) { int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; using (Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))) { ZipEntry entry = new ZipEntry(fileNameForZip); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
///<summary> ///递归压缩文件夹方法 ///</summary> ///<param name="FolderToZip"></param> ///<param name="s"></param> ///<param name="ParentFolderName"></param> private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[avg]; entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); for (int i = 0; i < fs.Length; i += avg) { if (i + avg > fs.Length) { //不足100MB的部分写剩余部分 buffer = new byte[fs.Length - i]; } fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, buffer.Length); } } } catch (Exception ex) { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
void NewCompress(string sZipFileFullPathName,SPList sList) { SPSecurity.RunWithElevatedPrivileges(delegate { ZipOutputStream zs = new ZipOutputStream(File.Create(sZipFileFullPathName));//D:/project/Dowload/DownLoadFile/1-2-3.zip zs.SetLevel(0); foreach (string sId in sIDS.Split('-')) { SPListItem item = sList.GetItemById(int.Parse(sId)); iParentFolderLength=item.Url.LastIndexOf('/')+1; NewCreateZip(item, zs); } zs.Finish(); zs.Close(); GC.Collect(); }); }
public static void SignPackage(Stream input, X509Certificate2 certificate, Stream output, bool signWholeFile) { JarFile inputJar = null; ZipOutputStream outputJar = null; // Assume the certificate is valid for at least an hour. DateTime timestamp; DateTime.TryParse(certificate.GetEffectiveDateString(), out timestamp); timestamp = timestamp.AddHours(1); //DateTime timestamp = DateTime.Parse(certificate.GetEffectiveDateString()).AddHours(1); inputJar = new JarFile(input); // Don't verify. Stream outputStream = null; if (signWholeFile) { outputStream = new MemoryStream(); } else { outputStream = output; } outputJar = new ZipOutputStream(outputStream); outputJar.SetComment(null); outputJar.SetLevel(9); JarEntry je; Manifest manifest = addDigestsToManifest(inputJar); // Everything else copyFiles(manifest, inputJar, outputJar, timestamp); // otacert if (signWholeFile) { addOtacert(outputJar, certificate, timestamp, manifest); } var buffer = new MemoryStream(); // MANIFEST.MF je = new JarEntry(JarFile.MANIFEST_NAME); je.DateTime = timestamp; manifest.Write(buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); // CERT.SF var signature = new MemoryStream(); je = new JarEntry(CERT_SF_NAME); je.DateTime = timestamp; buffer.SetLength(0); writeSignatureFile(manifest, signature); signature.WriteTo(buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); // CERT.RSA je = new JarEntry(CERT_RSA_NAME); je.DateTime = timestamp; buffer.SetLength(0); writeSignatureBlock(signature, certificate, buffer); je.Size = buffer.Length; outputJar.PutNextEntry(je); buffer.WriteTo(outputJar); outputJar.Close(); outputJar = null; if (signWholeFile) { signWholeOutputFile(((MemoryStream)outputStream).ToArray(), output, certificate); } }
/// <summary>Deflates the specified input using Telerik.Windows.Zip.</summary> public static byte[] Deflate(string input) { using (var output = new MemoryStream()) { using (var gzip = new ZipOutputStream(output, ZipCompression.Deflated)) using (var writer = new StreamWriter(gzip, Encoding.UTF8)) writer.Write(input); return output.ToArray(); } }
/// <summary> /// 檔案 Zip 壓縮 /// </summary> /// <param name="pi_sSetZipFolderPath">放進壓縮檔的資料夾路徑</param> /// <param name="pi_sCreateZipFolderPath">建立壓縮檔的資料夾路徑</param> /// <param name="pi_sZipFileName">壓縮檔檔名(含副檔名)</param> public void ZipFiles(string pi_sSetZipFolderPath, string pi_sCreateZipFolderPath, string pi_sZipFileName) { ZipOutputStream zos = null; try { string zipPath = pi_sCreateZipFolderPath + @"\" + pi_sZipFileName; ArrayList files = new ArrayList(); byte[] buffer = new byte[4096]; List <string> objFolderNameList = new List <string>(); if (Directory.Exists(pi_sSetZipFolderPath)) { files.AddRange(Directory.GetFiles(pi_sCreateZipFolderPath, "*.*", SearchOption.AllDirectories)); } zos = new ZipOutputStream(File.Create(zipPath)); //if (pi_sPassword != null && pi_sPassword != string.Empty) zos.Password = pi_sPassword; //if (pi_sComment != null && pi_sComment != "") zos.SetComment(pi_sComment); zos.SetLevel(9); //Compression level 0-9 (9 is highest) zos.UseZip64 = UseZip64.Off; foreach (string f in files) { FileInfo objFile = new FileInfo(f); string sFilePath = objFile.FullName.Replace(pi_sSetZipFolderPath + @"\", ""); ZipEntry entry = new ZipEntry(sFilePath); //objFile.Directory.FullName.Replace(pi_sSetZipFolderPath, "").Replace(@"\", "") if (!string.IsNullOrEmpty(objFile.Directory.FullName.Replace(pi_sSetZipFolderPath, "").Replace(@"\", "")) && !objFolderNameList.Contains(objFile.Directory.Name)) { ZipEntry objFolder = new ZipEntry(objFile.Directory.Name + @"\"); objFolder.DateTime = DateTime.Now; zos.PutNextEntry(objFolder); objFolderNameList.Add(objFile.Directory.Name); } entry.DateTime = DateTime.Now; zos.PutNextEntry(entry); FileStream fs = File.OpenRead(f); int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); zos.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); fs.Close(); fs.Dispose(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { zos.Finish(); zos.Close(); zos.Dispose(); } }
internal void Save(Stream stream) { var enc = Encoding.UTF8; ZipOutputStream os = new ZipOutputStream(stream, true); os.CompressionLevel = (OfficeOpenXml.Packaging.Ionic.Zlib.CompressionLevel)_compression; /**** ContentType****/ var entry = os.PutNextEntry("[Content_Types].xml"); byte[] b = enc.GetBytes(GetContentTypeXml()); os.Write(b, 0, b.Length); /**** Top Rels ****/ _rels.WriteZip(os, "_rels\\.rels"); ZipPackagePart ssPart=null; foreach(var part in Parts.Values) { if (part.ContentType != ExcelPackage.contentTypeSharedString) { part.WriteZip(os); } else { ssPart = part; } } //Shared strings must be saved after all worksheets. The ss dictionary is populated when that workheets are saved (to get the best performance). if (ssPart != null) { ssPart.WriteZip(os); } os.Flush(); os.Close(); os.Dispose(); //return ms; }
private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName) { bool flag = true; ZipEntry entry = null; FileStream stream = null; Crc32 crc = new Crc32(); try { if (i++ == 0) { currentZipFolder = FolderToZip; } string[] files = Directory.GetFiles(FolderToZip); foreach (string str in files) { //压缩文件为选中的状态 if (zipFiles.Contains(str)) { stream = File.OpenRead(str); byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(str))) { DateTime = DateTime.Now, Size = stream.Length }; stream.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } catch { flag = false; } finally { if (stream != null) { stream.Close(); stream = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } string[] directories = Directory.GetDirectories(FolderToZip); foreach (string str2 in directories) { //压缩文件夹为选中的状态 if (zipFiles.Contains(str2)) { string parentFolder = str2.Replace(currentZipFolder + "\\", ""); if (!ZipFileDictory(str2, s, parentFolder)) { return(false); } } } return(flag); }
/// <summary> /// 递归压缩文件夹方法 /// </summary> /// <param name="FolderToZip"></param> /// <param name="s"></param> /// <param name="ParentFolderName"></param> private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName) { bool res = true; string[] folders, filenames; ZipEntry entry = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { //打开压缩文件 using (var fs = File.OpenRead(file)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } finally { if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
private void btnAddPrint_Click(object sender, EventArgs e) //método que adiciona o print no form e prepara para salvar { try { DateTime dataSalvamento; dataSalvamento = DateTime.Now; string caminhoSalvo = PastaAPP.resgataPastaPadrao() + @"\arquivosControle\catapora\catapora" + dataSalvamento.ToString("HH-mm-ss_dd-MMM-yyyy") + ".zip"; //################### FUNCIONA ###################### if (ofdCompactar.ShowDialog() == System.Windows.Forms.DialogResult.OK) { char delimitador = '\\'; //delimitador das pastas, vai separar pastas dos arquivos string nomeArquivoFim; //variavel que vai pegar o nome do arquivo pra salvar string[] nomeArquivo; //array que vai pegar separadamente cada pasta e por fim o nome do arquivo string nomeZip = ofdCompactar.FileName; nomeArquivo = nomeZip.Split(delimitador); nomeArquivoFim = nomeArquivo.Last(); ZipOutputStream zipOutPut = new ZipOutputStream(File.Create(caminhoSalvo)); //cria um arquivo zipado na pasta para ser incluido dentro arquivos zipOutPut.SetLevel(6); //nível de compactação. 9 é o máximo //zipOutPut.Password = "******"; //bota senha no zip //ZipEntry arquivoSalvo = new ZipEntry(nomeArquivoFim);//Aqui vai o arquivo que será salvo //zipOutPut.PutNextEntry(arquivoSalvo); //aqui seto ele no arquivo zipOutPut.Finish(); //finaliza o arquivo zipOutPut.Close(); //fecha o arquivo ZipFile arquivoZip = new ZipFile(caminhoSalvo); //aqui converto o arquivo criado para zip da biblioteca arquivoZip.BeginUpdate(); //inicia a criação do ZIP // arquivoZip.NameTransform = new ZipNameTransform(nomeZip.Substring(1, nomeZip.LastIndexOf("/"))); foreach (string arquivos in ofdCompactar.FileNames) { string[] pegaNomesFinal; pegaNomesFinal = arquivos.Split(delimitador); string final = pegaNomesFinal.Last(); arquivoZip.Add(arquivos.ToString(), final); //primeiro parametro é o caminho do arquivo, segundo o arquivo em si } arquivoZip.CommitUpdate(); arquivoZip.Close(); } txtAnexoPrint.Text = caminhoSalvo; pctPrint.Load(System.Windows.Forms.Application.StartupPath + @"\image\outroformato.png"); } catch (Exception ex) { MessageBox.Show("Não foi possível salvar o arquivo. Informe o código do erro: " + ex.Message, "ERRO AO SALVAR BKP", MessageBoxButtons.OK, MessageBoxIcon.Error); } //########################### FUNCIONA COM UM ÚNICO ARQUIVO //if (ofdCompactar.ShowDialog() == DialogResult.OK) //{//tem que setar o multiselect como true nos atributos // char delimitador = '\\'; //delimitador das pastas, vai separar pastas dos arquivos // string nomeArquivoFim; //variavel que vai pegar o nome do arquivo pra salvar // string[] nomeArquivo; //array que vai pegar separadamente cada pasta e por fim o nome do arquivo // string nomeZip = ofdCompactar.FileName; // nomeArquivo = nomeZip.Split(delimitador); // nomeArquivoFim = nomeArquivo.Last(); // int TAMANHO_STREAM = 4096; // FileStream objStreamDestino = // new FileStream(System.Windows.Forms.Application.StartupPath + @"\image\Exemplo.zip", FileMode.Create, FileAccess.Write); // //Arquivo que vai ser gerado // FileStream arquivo = new FileStream(ofdCompactar.FileName, FileMode.Open, FileAccess.Read); // //Arquivo que será compactado // ZipOutputStream objZipDestino = new ZipOutputStream(objStreamDestino); // // objZipDestino.Password = "******"; //coloca senha no zip // objZipDestino.SetLevel(5);//nível de compactação. máximo é 9 // // Aqui informamos qual será a senha para acesso ao arquivo zip // try // { // byte[] buffer = new byte[TAMANHO_STREAM]; // //Criando um array para servir como armazenador durante a iteração sobre o objeto. // foreach (string arquivos in ofdCompactar.FileNames) // { // string[] pegaNomesFinal; // pegaNomesFinal = arquivos.Split(delimitador); // string final = pegaNomesFinal.Last(); // ZipEntry entrada = new ZipEntry(final); /* Criando uma nova entrada de arquivos, //já já entenderemos melhor o que isso significa. //Devemos passar como parâmetro o nome do arquivo que será inserido no .zip, //NÃO devemos colocar o caminho do arquivo que será compactado somente o nome.*/ // objZipDestino.PutNextEntry(entrada); // // Aqui adicionamos no arquivo destino à entrada de arquivo que criamos na linha acima. // objZipDestino.Password = "******"; // // Aqui informamos qual será a senha para acesso ao arquivo zip // int bytesLidos = 0; // do // { // bytesLidos = arquivo.Read(buffer, 0, TAMANHO_STREAM); // /* lendo o arquivo a ser compactado, // os bytes lidos são colocados no array buffer e a da quantidade e // bytes lidos é inserida na variável bytesLidos o valor do terceiro // parâmetro deve ser o mesmo que colocamos no tamanho do array buffer*/ // objZipDestino.Write(buffer, 0, bytesLidos);/*escrevendo no arquivo zipado, // o buffer contém os dados que devem ser inseridos e a variável bytesLidos // informa ao método quantos bytes contidos no buffer ele deve realmente inserir. // Tendo em vista que: digamos que só haja 2 bytes no arquivo de origem, // as duas primeiras posições do array buffer seriam preenchidas as outras // permaneceriam vazias, você não quer que bytes vazios sejam inseridos no seu // .ZIP pois estes podem corrompe-lo, portando é de suma importância saber realmente // quantos bytes são relevantes dentro do array*/ // } // while (bytesLidos > 0); // // enquanto o número de bytes lidos é maior que zero faz-se o loop // /*é importante entender que a informação é lida e escrita em blocos, nesse caso ele // Lê 4096 bytes // Insere 4096 bytes // Lê 4096 bytes // Insere 4096 bytes // E assim vai até não haver mais bytes a serem lidos. // */ // } // } // catch (Exception ex) // { // MessageBox.Show("Erro: " + ex.Message); // //throw ex; // Aqui devemos tratar se algum erro ocorrer neste // //caso estou repassando a bucha para o método que chamou. // } // finally // { // //fechando as comunicações. // arquivo.Close(); // objZipDestino.Close(); // objStreamDestino.Close(); // } //} }
/// <summary> /// Creates a ZIP archive, returned as a <see cref="ZipOutputStream"/>, containing the specified <paramref name="albumIds">albums /// </paramref> and <paramref name="mediaObjectIds">media objects</paramref>. Only media objects associated with a /// physical file are included (in other words, external media objects are excluded). The archive is created in memory /// and is not stored on disk. /// </summary> /// <param name="parentAlbumId">The ID of the album containing the <paramref name="albumIds"/> and <paramref name="mediaObjectIds"/>. /// When <paramref name="albumIds"/> or <paramref name="mediaObjectIds"/> belong to more than one album, such as when a user is /// downloading multiple albums contained within a virtual album, specify <see cref="Int32.MinValue"/>.</param> /// <param name="albumIds">The ID's of the albums to add to the ZIP archive. It's child albums and media objects are recursively /// added. Each album must exist within the parent album, but does not have to be an immediate child (it can be a grandchild, etc).</param> /// <param name="mediaObjectIds">The ID's of the media objects to add to the archive. Each media object must exist within the parent album, /// but does not have to be an immediate child (it can be a grandchild, etc).</param> /// <param name="imageSize">Size of the image to add to the ZIP archive. This parameter applies only to <see cref="Image"/> /// media objects.</param> /// <returns>Returns a <see cref="MemoryStream"/> of a ZIP archive that contains the specified albums and media objects.</returns> public Stream CreateZipStream(int parentAlbumId, List<int> albumIds, List<int> mediaObjectIds, DisplayObjectType imageSize) { string currentItemBasePath; string basePath = null; bool applyWatermark = true; // Will be overwritten later try { // Get the path to the parent album. This will fail when parentAlbumId does not refer to a valid album. basePath = String.Concat(Factory.LoadAlbumInstance(parentAlbumId, false).FullPhysicalPathOnDisk, Path.DirectorySeparatorChar); applyWatermark = this.DetermineIfWatermarkIsToBeApplied(parentAlbumId); } catch (ErrorHandler.CustomExceptions.InvalidAlbumException) { /* Ignore for now; we'll check basePath later */ } MemoryStream ms = new MemoryStream(); ZipOutputStream zos = new ZipOutputStream(ms); zos.SetLevel(ZIP_COMPRESSION_LEVEL); if (albumIds != null) { foreach (int albumId in albumIds) { IAlbum album = Factory.LoadAlbumInstance(albumId, true); if (String.IsNullOrEmpty(basePath)) { // The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path // of the current album's parent. currentItemBasePath = String.Concat(album.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar); applyWatermark = DetermineIfWatermarkIsToBeApplied(albumId); } else { currentItemBasePath = basePath; } AddZipEntry(zos, album, imageSize, currentItemBasePath, applyWatermark); } } if (mediaObjectIds != null) { foreach (int mediaObjectId in mediaObjectIds) { IGalleryObject mediaObject = Factory.LoadMediaObjectInstance(mediaObjectId); if (String.IsNullOrEmpty(basePath)) { // The base path wasn't assigned because albumParentId does not refer to a valid album. Instead we will use the path // of the current media object's album. currentItemBasePath = String.Concat(mediaObject.Parent.FullPhysicalPathOnDisk, Path.DirectorySeparatorChar); applyWatermark = DetermineIfWatermarkIsToBeApplied(mediaObject.Parent.Id); } else { currentItemBasePath = basePath; } AddFileZipEntry(zos, mediaObject, imageSize, currentItemBasePath, applyWatermark); } } zos.Finish(); return ms; }
protected override void Do() { try { SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.Init); CoreContext.TenantManager.SetCurrentTenant(CurrentTenant); try { SecurityContext.AuthenticateMe(CurrentUser); } catch { Error = Resource.SsoSettingsNotValidToken; Logger.Error(Error); } var engine = new EngineFactory(CurrentTenant.TenantId, CurrentUser.ID.ToString()); SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.GetAttachments); var attachments = engine.AttachmentEngine.GetAttachments(new ConcreteMessageAttachmentsExp(MessageId, CurrentTenant.TenantId, CurrentUser.ID.ToString())); if (!attachments.Any()) { Error = MailCoreResource.NoAttachmentsInMessage; throw new Exception(Error); } SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.Zipping); var damagedAttachments = 0; using (var stream = TempStream.Create()) { using (var zip = new ZipOutputStream(stream, true)) { zip.CompressionLevel = CompressionLevel.Level3; zip.AlternateEncodingUsage = ZipOption.AsNecessary; zip.AlternateEncoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage); var attachmentsCount = attachments.Count; var progressMaxValue = (int)MailOperationDownloadAllAttachmentsProgress.ArchivePreparation; var progressMinValue = (int)MailOperationDownloadAllAttachmentsProgress.Zipping; var progresslength = progressMaxValue - progressMinValue; var progressStep = (double)progresslength / attachmentsCount; var zippingProgress = 0.0; foreach (var attachment in attachments) { try { using (var file = attachment.ToAttachmentStream()) { ZipFile(zip, file.FileName, file.FileStream); } } catch (Exception ex) { Logger.Error(ex); Error = string.Format(MailCoreResource.FileNotFoundOrDamaged, attachment.fileName); damagedAttachments++; ZipFile(zip, attachment.fileName); // Zip empty file } zippingProgress += progressStep; SetProgress(progressMinValue + (int?)zippingProgress); } } SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.ArchivePreparation); if (stream.Length == 0) { Error = "File stream is empty"; throw new Exception(Error); } stream.Position = 0; var store = Global.GetStore(); var path = store.Save( FileConstant.StorageDomainTmp, string.Format(@"{0}\{1}", ((IAccount)Thread.CurrentPrincipal.Identity).ID, Defines.ARCHIVE_NAME), stream, "application/zip", "attachment; filename=\"" + Defines.ARCHIVE_NAME + "\""); Log.DebugFormat("Zipped archive has been stored to {0}", path.ToString()); } SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.CreateLink); var baseDomain = CoreContext.Configuration.BaseDomain; var source = string.Format("{0}?{1}=bulk", "/products/files/httphandlers/filehandler.ashx", FilesLinkUtility.Action); if (damagedAttachments > 1) { Error = string.Format(MailCoreResource.FilesNotFound, damagedAttachments); } SetProgress((int?)MailOperationDownloadAllAttachmentsProgress.Finished, null, source); } catch (Exception ex) { Logger.ErrorFormat("Mail operation error -> Download all attachments: {0}", ex.ToString()); Error = string.IsNullOrEmpty(Error) ? "InternalServerError" : Error; } }
/// <summary> /// Adds the media objects in the <paramref name="album"/> to the ZIP archive. Only media objects associated with a /// physical file are added (that is, external media objects are excluded). /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="album">The album to be added to the ZIP archive.</param> /// <param name="imageSize">Size of the image to add to the ZIP archive. This parameter applies only to <see cref="Image"/> /// media objects.</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only for media objects in the <see cref="album"/> that are an <see cref="Image"/>.</param> private void AddZipEntry(ZipOutputStream zos, IAlbum album, DisplayObjectType imageSize, string basePath, bool applyWatermark) { foreach (IAlbum childAlbum in album.GetChildGalleryObjects(GalleryObjectType.Album, false, !this._isAuthenticated)) { AddZipEntry(zos, childAlbum, imageSize, basePath, applyWatermark); } foreach (IGalleryObject mediaObject in album.GetChildGalleryObjects(GalleryObjectType.MediaObject, false, !this._isAuthenticated)) { AddFileZipEntry(zos, mediaObject, imageSize, basePath, applyWatermark); } }
void Backup() { string dumpFileName = GetSvnAdminDumpFileName(); using (var process = new Process()) { ConsoleEx.WriteLine("{0} repository commencing dump to {1}", GetRepoName(), dumpFileName); Func <string, string> quote = (inputStr) => "\"" + inputStr + "\""; var batchFileName = GetSvnAdminDumpBatchFileName(); using (var batchFile = File.CreateText(batchFileName)) { string[] args = { "dump", quote(RepoPath), ">", quote(dumpFileName) }; List <string> parts = new List <string>(); parts.Add(quote(Path.Combine(SvnPath, "svnadmin"))); parts.AddRange(args); var batchFileContents = String.Join(" ", parts.ToArray()); batchFile.WriteLine(batchFileContents); } process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = ""; process.StartInfo.FileName = batchFileName; process.StartInfo.UseShellExecute = false; process.Start(); process.WaitForExit(); long totalReadBytes = new FileInfo(dumpFileName).Length; ConsoleEx.WriteLine("{0} repository successfully dumped to {1} with size of {2} bytes", GetRepoName(), dumpFileName, totalReadBytes); // delete the batch file try { File.Delete(batchFileName); } catch (Exception ex) { ConsoleEx.WriteLine("Warning! Could not delete batch file {0} - Exception message {1}", batchFileName, ex.Message); } } if (!File.Exists(dumpFileName)) { throw new Exception("The dumpings of svnadmin doesn't exist. svnadmin failed in it's duty"); } if (ZipFile) { // zip up dump file string zipFileName = GetZipFileName(); ConsoleEx.WriteLine("{0} repository commencing zipping to {1}", GetRepoName(), zipFileName); // Depending on the directory this could be very large and would require more attention // in a commercial package. string[] filenames = { dumpFileName }; // 'using' statements gaurantee the stream is closed properly which is a big source // of problems otherwise. Its exception safe as well which is great. using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFileName))) { s.SetLevel(9); // 0 - store only to 9 - means best compression byte[] buffer = new byte[4096]; foreach (string file in filenames) { // Using GetFileName makes the result compatible with XP // as the resulting path is not absolute. ZipEntry entry = new ZipEntry(Path.GetFileName(GetDumpFileName())); // Setup the entry data as required. // Crc and size are handled by the library for seakable streams // so no need to do them here. // Could also use the last write time or similar for the file. entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { // Using a fixed size buffer here makes no noticeable difference for output // but keeps a lid on memory usage. int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // NOTE by Vijay: Finish/Close arent needed strictly as the using() disposal will call these automagically // Finish is important to ensure trailing information for a Zip file is appended. Without this // the created file would be invalid. s.Finish(); // Close is important to wrap things up and unlock the file. s.Close(); ConsoleEx.WriteLine("{0} repository successfully zipped to {1}", GetRepoName(), zipFileName); } } }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="isImage">Indicates whether the file specified in <paramref name="filePath"/> is an image. If it /// is, and <paramref name="applyWatermark"/> is <c>true</c>, a watermark is applied to the image as it is inserted /// into the archive.</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only when <paramref name="isImage"/> is <c>true</c>.</param> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath, bool isImage, bool applyWatermark) { int bufferSize = Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; #region Determine ZIP entry name // Get name of the file as it will be stored in the ZIP archive. This is the fragment of the full file path // after the base path. Ex: If basePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\" // and filePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg", // then zipEntryName="desert sunsets\zOpt_sonorandesert.jpg". The ZIP algorithm will automatically sense the // embedded directory ("desert sunsets") and create it. string zipEntryName; if (String.IsNullOrEmpty(fileNameForZip)) { zipEntryName = filePath.Replace(basePath, String.Empty); } else { zipEntryName = fileNameForZip.Replace(basePath, String.Empty); } #endregion using (Stream stream = CreateStream(filePath, isImage, applyWatermark)) { ZipEntry entry = new ZipEntry(zipEntryName); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
public void Zip64Descriptor() { MemoryStream msw = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.Off; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); var ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } msw = new MemoryStreamWithoutSeek(); outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.On; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } }
public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZOS() { // Verify that unsetting the Encryption property after // setting a Password results in no encryption being used. // This method tests ZipOutputStream. string unusedPassword = TestUtilities.GenerateRandomPassword(); int numTotalEntries = _rnd.Next(46)+653; string zipFileToCreate = "UnsetEncryption.zip"; using (FileStream fs = File.Create(zipFileToCreate)) { using (var zos = new ZipOutputStream(fs)) { zos.Password = unusedPassword; zos.Encryption = EncryptionAlgorithm.None; for (int i=0; i < numTotalEntries; i++) { if (_rnd.Next(7)==0) { string entryName = String.Format("{0:D5}/", i); zos.PutNextEntry(entryName); } else { string entryName = String.Format("{0:D5}.txt", i); zos.PutNextEntry(entryName); if (_rnd.Next(12)==0) { var block = TestUtilities.GenerateRandomAsciiString() + " "; string contentBuffer = String.Format("This is the content for entry {0}", i); int n = _rnd.Next(6) + 2; for (int j=0; j < n; j++) contentBuffer += block; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer); zos.Write(buffer, 0, buffer.Length); } } } } } BasicVerifyZip(zipFileToCreate); }
public static void CopyEntries(ZipFile from, ZipOutputStream to) { CopyEntries(from, to, null); }