Ejemplo n.º 1
2
        /// <summary>
        /// Creates a zip archive from a byte array
        /// </summary>
        /// <param name="buffer">The file in byte[] format</param>
        /// <param name="fileName">The name of the file you want to add to the archive</param>
        /// <returns></returns>
        public static byte[] CreateZipByteArray(byte[] buffer, string fileName)
        {
            ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();

            using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream())
            {
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream);

                zipOutputStream.SetLevel(6);

                ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
                zipEntry.DateTime = DateTime.Now;
                zipEntry.Size = buffer.Length;

                crc.Reset();
                crc.Update(buffer);
                zipEntry.Crc = crc.Value;
                zipOutputStream.PutNextEntry(zipEntry);
                zipOutputStream.Write(buffer, 0, buffer.Length);

                zipOutputStream.Finish();

                byte[] zipByteArray = new byte[zipMemoryStream.Length];
                zipMemoryStream.Position = 0;
                zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length);

                zipOutputStream.Close();

                return zipByteArray;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Zips the specified <paramref name="baseFolder"/> to  the <paramref name="stream"/>.
        /// </summary>
        /// <param name="stream">Stream to write the compressed data to.</param>
        /// <param name="baseFolder">The folder to zip</param>
        /// <param name="filesToZip">
        /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. 
        /// These names are only matched in the <paramref name="baseFolder"/> but not recursive.
        /// You can use the default globbing (* and ?).
        /// </param>
        /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param>
        public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore)
        {
            using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream))
             {
            s.SetLevel(9);
            s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off;
            var baseDir = new DirectoryInfo(baseFolder);
            foreach (var fileMask in filesToZip)
            {
               foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly))
               {
                  if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue;
                  var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name);
                  s.PutNextEntry(zipEntry);
                  using (var fileStream = file.OpenRead()) fileStream.CopyTo(s);
               }
               foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly))
               {
                  if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue;
                  ZipDirectory(s, baseDir, subDir, filesToIgnore);
               }

            }
            s.Finish();
             }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    stream.SetLevel(0);
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        var data = filenamesAndData[filename];
                        var bytes = Encoding.Default.GetBytes(data);
                        stream.PutNextEntry(entry);
                        stream.Write(bytes, 0, bytes.Length);
                        stream.CloseEntry();
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                return false;
            }
            return true;
        }
Ejemplo n.º 4
0
		bool Zip ()
		{
			var xapName = XapFilename.ItemSpec;
			if (File.Exists (xapName)) {
				DateTime lastMod = File.GetLastWriteTime (xapName);
				bool needsWrite = false;
				foreach (ITaskItem file_item in InputFiles) {
					if (File.GetLastWriteTime (file_item.ItemSpec) > lastMod) {
						needsWrite = true;
						break;
					}
				}
				if (!needsWrite) {
					Log.LogMessage (MessageImportance.Low, "Skipping xap file {0} generation, its up-to date");
					return true;
				}
			}

			Log.LogMessage (MessageImportance.Normal, "Generating compressed xap file {0}", xapName);
			try {
				using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
					var zip_stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
					zip_stream.SetLevel (9);

					AddFilesToZip (InputFiles, zip_stream);
					AddFilesToZip (LocalCopyReferences, zip_stream);

					zip_stream.Finish ();
					zip_stream.Close ();
				}
			} catch (IOException ex) {
				Log.LogError ("Error writing xap file.", ex);
				Log.LogMessage (MessageImportance.Low, "Error writing xap file:" + ex.ToString ());

				try {
					if (File.Exists (xapName))
						File.Delete (xapName);
				} catch {}

				return false;
			}

			return true;
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        //Get a Byte[] of the file data:
                        var file = Encoding.Default.GetBytes(filenamesAndData[filename]);
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return success;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="zipEntryName">The name of the entry inside the zip file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, string zipEntryName, bool deleteOriginal = true)
        {
            var zipPath = "";

            try
            {
                var buffer = new byte[4096];
                zipPath = textPath.Replace(".csv", ".zip");
                zipPath = zipPath.Replace(".txt", ".zip");
                //Open the zip:
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(zipEntryName);
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(textPath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }while (sourceBytes > 0);
                    }
                    //Close stream:
                    stream.Finish();
                    stream.Close();
                }
                //Delete the old text file:
                if (deleteOriginal)
                {
                    File.Delete(textPath);
                }
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.Zip(): " + err.Message);
            }
            return(zipPath);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Create a zip file of the supplied file names and string data source
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully creating the zip file.</returns>
        public static bool ZipData(string zipPath, Dictionary <string, string> filenamesAndData)
        {
            var success = true;
            var buffer  = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var filename in filenamesAndData.Keys)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(filename);
                        //Get a Byte[] of the file data:
                        var file = Encoding.Default.GetBytes(filenamesAndData[filename]);
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error(err);
                success = false;
            }
            return(success);
        }
Ejemplo n.º 8
0
        private byte[] CompressFile(byte[] data)
        {
            Stream stream = new MemoryStream(data);

            // Compress
            using (MemoryStream fsOut = new MemoryStream())
            {
                using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut))
                {
                    zipStream.SetLevel(3);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("data.xml");
                    newEntry.DateTime = DateTime.UtcNow;
                    zipStream.PutNextEntry(newEntry);
                    //zipStream.Write(data, 0, data.Length);
                    StreamUtils.Copy(stream, zipStream, new byte[2048]);
                    zipStream.Finish();
                    zipStream.Close();
                }
                return(fsOut.ToArray());
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create a zip file of the supplied file names and data using a byte array
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully saving the file</returns>
        public static bool ZipData(string zipPath, IEnumerable <KeyValuePair <string, byte[]> > filenamesAndData)
        {
            var success = true;
            var buffer  = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.ZipData(): " + err.Message);
                success = false;
            }
            return(success);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Compacta a lista de Arquivos criando o arquivo zip passado como parâmetro
        /// </summary>
        /// <param name="filesName">Lista de arquivos a serem incluidos no .zip</param>
        /// <param name="strArquivoZip">Nome do arquivo .zip</param>
        public void compacta(ref System.Collections.ArrayList filesName, string strArquivoZip)
        {
            try
            {
                ICSharpCode.SharpZipLib.Checksums.Crc32     clsCrc          = new ICSharpCode.SharpZipLib.Checksums.Crc32();
                ICSharpCode.SharpZipLib.Zip.ZipOutputStream clsZipOutStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(strArquivoZip));

                clsZipOutStream.SetLevel(m_nNivelCompressao);

                foreach (string file in filesName)
                {
                    System.IO.FileStream fs = System.IO.File.OpenRead(file);

                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file);

                    entry.DateTime = DateTime.Now;

                    entry.Size = fs.Length;
                    fs.Close();

                    clsCrc.Reset();
                    clsCrc.Update(buffer);

                    entry.Crc = clsCrc.Value;

                    clsZipOutStream.PutNextEntry(entry);

                    clsZipOutStream.Write(buffer, 0, buffer.Length);
                }
                clsZipOutStream.Finish();
                clsZipOutStream.Close();
            }
            catch (Exception err)
            {
                Object erro = err;
                m_cls_ter_tratadorErro.trataErro(ref erro);
            }
        }
        public void ZipAdminFile(string strFile, List <string> filesExtra)
        {
            if (File.Exists(strFile))
            {
                if (GetConfig().ZipAfterIndexed == true)
                {
                    try
                    {
                        string zipFilePath = Path.ChangeExtension(strFile, ".zip");
                        if (File.Exists(zipFilePath))
                        {
                            File.Delete(zipFilePath);
                        }

                        if (filesExtra == null)
                        {
                            filesExtra = new List <string>();
                        }
                        if (strFile != null)
                        {
                            filesExtra.Add(strFile);
                        }

                        ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream);
                        strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath));

                        if (GetConfig().CollapseFolders)
                        {
                            // minus.gif
                            string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif";
                            if (File.Exists(f1))
                            {
                                filesExtra.Add(f1);
                            }
                            string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif";
                            if (File.Exists(f2))
                            {
                                filesExtra.Add(f2);
                            }
                        }

                        if (File.Exists(GetConfig().LogoPath))
                        {
                            filesExtra.Add(GetConfig().LogoPath);
                        }

                        foreach (string filePath in filesExtra)
                        {
                            FileStream strmFile  = File.OpenRead(filePath);
                            byte[]     abyBuffer = new byte[(int)strmFile.Length - 1 + 1];
                            strmFile.Read(abyBuffer, 0, abyBuffer.Length);

                            ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath));
                            objZipEntry.DateTime = DateTime.Now;
                            objZipEntry.Size     = strmFile.Length;
                            strmFile.Close();

                            strmZipOutputStream.PutNextEntry(objZipEntry);

                            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
                        }

                        ///'''''''''''''''''''''''''''''''''
                        // Finally Close strmZipOutputStream
                        ///'''''''''''''''''''''''''''''''''
                        strmZipOutputStream.Finish();
                        strmZipOutputStream.Close();

                        if (GetConfig().ZipAndDeleteFile == true)
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
		BuildResult Zip (IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf)
		{
			var xapName = GetXapName (proj, conf);
			
			var src = new List<string> ();
			var targ = new List<string> ();
			
			src.Add (conf.CompiledOutputName);
			targ.Add (conf.CompiledOutputName.FileName);
			
			// FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap,
			// when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers 
			// that read pdb files don't expect them to be in the xap.
			var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime;
			
			if (doSdbCopy) {
				FilePath mdb = conf.CompiledOutputName + ".mdb";
				if (File.Exists (mdb)) {
					src.Add (mdb);
					targ.Add (mdb.FileName);
				}
			}

			if (proj.GenerateSilverlightManifest) {
				src.Add (conf.OutputDirectory.Combine ("AppManifest.xaml"));
				targ.Add ("AppManifest.xaml");
			}

			foreach (ProjectFile pf in proj.Files) {
				if (pf.BuildAction == BuildAction.Content) {
					src.Add (pf.FilePath);
					targ.Add (pf.ProjectVirtualPath);
				}
			}
			
			BuildResult res = new BuildResult ();

			// The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles.
			// Instead we need to iterate over the refs and handle them manually.
			foreach (ProjectReference pr in proj.References) {
				if (pr.LocalCopy) {
					var pk = pr.Package;
					if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith ("-redist")) {
						string err = pr.ValidationErrorMessage;
						if (!String.IsNullOrEmpty (err)) {
							string msg = String.Format ("Could not add reference '{0}' to '{1}': {2}",
							                            pr.Reference, xapName.FileName, err);
							res.AddError (msg);
							monitor.Log.WriteLine (msg);
							continue;
						}
						foreach (string s in pr.GetReferencedFileNames (slnConf)) {
							src.Add (s);
							targ.Add (Path.GetFileName (s));
							
							if (doSdbCopy && s.EndsWith (".dll")) {
								FilePath mdb = s + ".mdb";
								if (File.Exists (mdb)) {
									src.Add (mdb);
									targ.Add (mdb.FileName);
								}
							}
						}
					}
				}
			}
			
			if (res.ErrorCount > 0) {
				res.FailedBuildCount++;
				return res;
			}
			
			if (File.Exists (xapName)) {
				DateTime lastMod = File.GetLastWriteTime (xapName);
				bool needsWrite = false;
				foreach (string file in src) {
					if (File.GetLastWriteTime (file) > lastMod) {
						needsWrite = true;
						break;
					}
				}
				if (!needsWrite)
					return null;
			}
			
			monitor.Log.WriteLine ("Compressing XAP file...");
			
			try {
				using (FileStream fs = new FileStream (xapName, FileMode.Create)) {
					var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs);
					zipfile.SetLevel (9);
					
					byte[] buffer = new byte[4096];
					
					for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++) {
						zipfile.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (targ[i]));
						using (FileStream inStream = File.OpenRead (src[i])) {
							int readCount;
							do {
								readCount = inStream.Read (buffer, 0, buffer.Length);
								zipfile.Write (buffer, 0, readCount);
							} while (readCount > 0);
						}
					}
					if (!monitor.IsCancelRequested) {
						zipfile.Finish ();
						zipfile.Close ();
					}
				}
			} catch (IOException ex) {
				monitor.ReportError ("Error writing xap file.", ex);
				res.AddError ("Error writing xap file:" + ex.ToString ());
				res.FailedBuildCount++;
				
				try {
					if (File.Exists (xapName))                                                               
						File.Delete (xapName);
				} catch {}
				
				return res;
			}
			
			if (monitor.IsCancelRequested) {
				try {
					if (File.Exists (xapName))                                                               
						File.Delete (xapName);
				} catch {}
			}
			
			return res;
		}
        public void ZipAdminFile(string strFile, List<string> filesExtra)
        {
            if (File.Exists(strFile))
            {
                if (GetConfig().ZipAfterIndexed == true)
                {
                    try
                    {
                        string zipFilePath = Path.ChangeExtension(strFile, ".zip");
                        if (File.Exists(zipFilePath)) File.Delete(zipFilePath);

                        if (filesExtra == null)
                        {
                            filesExtra = new List<string>();
                        }
                        if (strFile != null)
                        {
                            filesExtra.Add(strFile);
                        }

                        ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream);
                        strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath));

                        if (GetConfig().CollapseFolders)
                        {
                            // minus.gif
                            string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif";
                            if (File.Exists(f1)) filesExtra.Add(f1);
                            string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif";
                            if (File.Exists(f2)) filesExtra.Add(f2);
                        }

                        if (File.Exists(GetConfig().LogoPath))
                        {
                            filesExtra.Add(GetConfig().LogoPath);
                        }

                        foreach (string filePath in filesExtra)
                        {
                            FileStream strmFile = File.OpenRead(filePath);
                            byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1];
                            strmFile.Read(abyBuffer, 0, abyBuffer.Length);

                            ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath));
                            objZipEntry.DateTime = DateTime.Now;
                            objZipEntry.Size = strmFile.Length;
                            strmFile.Close();

                            strmZipOutputStream.PutNextEntry(objZipEntry);

                            strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length);
                        }

                        ///'''''''''''''''''''''''''''''''''
                        // Finally Close strmZipOutputStream
                        ///'''''''''''''''''''''''''''''''''
                        strmZipOutputStream.Finish();
                        strmZipOutputStream.Close();

                        if (GetConfig().ZipAndDeleteFile == true)
                        {
                            File.Delete(strFile);
                        }
                    }
                    catch (System.UnauthorizedAccessException ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }
                }
            }
        }
Ejemplo n.º 14
0
        private static void compress_zip()
        {
            string zipPath   = bset.zip_path;
            string zipFolder = bset.tmp_folder_path;

            //Write ZIP Stream.
            FileStream writer = new FileStream(zipPath, FileMode.Create, FileAccess.Write);

            //Build ZipOutputStream.
            ICSharpCode.SharpZipLib.Zip.ZipOutputStream zos = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(writer);

            //Set compress levels.
            if ((0 <= bset.compress) | (9 >= bset.compress))
            {
                zos.SetLevel(bset.compress);
            }
            else
            {
                zos.SetLevel(9);
            }

            //Get folders.
            ICSharpCode.SharpZipLib.Zip.ZipNameTransform nameTrans =
                new ICSharpCode.SharpZipLib.Zip.ZipNameTransform(zipFolder);

            foreach (string file in Directory.EnumerateFiles(zipFolder, "*", System.IO.SearchOption.AllDirectories))
            {
                if (file == bset.zip_path)
                {
                    continue;
                }

                // Set file name.
                string f = nameTrans.TransformFile(file);
                ICSharpCode.SharpZipLib.Zip.ZipEntry ze =
                    new ICSharpCode.SharpZipLib.Zip.ZipEntry(f);

                // Set file informations.
                FileInfo fi = new System.IO.FileInfo(file);
                ze.DateTime = fi.LastAccessTime;
                ze.ExternalFileAttributes = (int)fi.Attributes;
                ze.Size          = fi.Length;
                ze.IsUnicodeText = true;
                zos.PutNextEntry(ze);

                // Load files.
                try
                {
                    FileStream fs     = new System.IO.FileStream(file, FileMode.Open, FileAccess.Read);
                    byte[]     buffer = new byte[2048];
                    int        len;
                    while ((len = fs.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zos.Write(buffer, 0, len);
                    }
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(" - Error: " + file + " [" + ex.Message + "]");
                    continue;
                }
            }
            // Close objects.
            zos.Finish();
            zos.Close();
            writer.Close();
        }
Ejemplo n.º 15
0
 private void menuExportTeamData_Click(object sender, EventArgs e)
 {
     SaveFileDialog d = new SaveFileDialog();
     d.AddExtension = true;
     d.DefaultExt = ".zip";
     d.Filter = T("Tutti i file ZIP (*.zip)")+"|*.zip";
     d.FileName = "RMO-Team-Data-" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip";
     d.InitialDirectory = My.Dir.Desktop;
     d.OverwritePrompt = true;
     d.Title = T("Nome del file da esportare");
     if (d.ShowDialog() == DialogResult.OK)
     {
         try
         {
             string[] filenames = System.IO.Directory.GetFiles(PATH_HISTORY, "*.team");
             progressBar.Value = 0;
             progressBar.Maximum = filenames.Length;
             using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(d.FileName)))
             {
                 s.SetLevel(9);
                 byte[] buffer = new byte[4096];
                 foreach (string file in filenames)
                 {
                     ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(file));
                     entry.DateTime = DateTime.Now;
                     s.PutNextEntry(entry);
                     using (System.IO.FileStream fs = System.IO.File.OpenRead(file))
                     {
                         int sourceBytes;
                         do
                         {
                             sourceBytes = fs.Read(buffer, 0, buffer.Length);
                             s.Write(buffer, 0, sourceBytes);
                         }
                         while (sourceBytes > 0);
                     }
                     progressBar.Value++;
                 }
                 s.Finish();
                 s.Close();
                 lStatus.Text = T("Esportazione del backup ultimata correttamente!");
             }
         }
         catch (Exception ex) { My.Box.Errore(T("Errore durante l'esportazione del backup")+"\r\n"+ex.Message); }
         progressBar.Value = 0;
     }
 }
Ejemplo n.º 16
0
        /// <summary>
        /// Compress a given file and delete the original file. Automatically rename the file to name.zip.
        /// </summary>
        /// <param name="textPath">Path of the original file</param>
        /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param>
        /// <returns>String path for the new zip file</returns>
        public static string Zip(string textPath, bool deleteOriginal = true)
        {
            var zipPath = "";

            try
            {
                var buffer = new byte[4096];
                zipPath = textPath.Replace(".csv", ".zip");
                zipPath = zipPath.Replace(".txt", ".zip");
                //Open the zip:
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    //Zip the text file.
                    var entry = new ZipEntry(Path.GetFileName(textPath));
                    stream.PutNextEntry(entry);

                    using (var fs = File.OpenRead(textPath))
                    {
                        int sourceBytes;
                        do
                        {
                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                            stream.Write(buffer, 0, sourceBytes);
                        }
                        while (sourceBytes > 0);
                    }
                    //Close stream:
                    stream.Finish();
                    stream.Close();
                }
                //Delete the old text file:
                if (deleteOriginal) File.Delete(textPath);
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.Zip(): " + err.Message);
            }
            return zipPath;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Create a zip file of the supplied file names and data using a byte array
        /// </summary>
        /// <param name="zipPath">Output location to save the file.</param>
        /// <param name="filenamesAndData">File names and data in a dictionary format.</param>
        /// <returns>True on successfully saving the file</returns>
        public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData)
        {
            var success = true;
            var buffer = new byte[4096];

            try
            {
                //Create our output
                using (var stream = new ZipOutputStream(File.Create(zipPath)))
                {
                    foreach (var file in filenamesAndData)
                    {
                        //Create the space in the zip file:
                        var entry = new ZipEntry(file.Key);
                        //Get a Byte[] of the file data:
                        stream.PutNextEntry(entry);

                        using (var ms = new MemoryStream(file.Value))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = ms.Read(buffer, 0, buffer.Length);
                                stream.Write(buffer, 0, sourceBytes);
                            }
                            while (sourceBytes > 0);
                        }
                    } // End For Each File.

                    //Close stream:
                    stream.Finish();
                    stream.Close();
                } // End Using
            }
            catch (Exception err)
            {
                Log.Error("QC.Data.ZipData(): " + err.Message);
                success = false;
            }
            return success;
        }
Ejemplo n.º 18
0
        BuildResult Zip(IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf)
        {
            var xapName = GetXapName(proj, conf);

            var src  = new List <string> ();
            var targ = new List <string> ();

            src.Add(conf.CompiledOutputName);
            targ.Add(conf.CompiledOutputName.FileName);

            // FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap,
            // when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers
            // that read pdb files don't expect them to be in the xap.
            var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime;

            if (doSdbCopy)
            {
                FilePath mdb = conf.CompiledOutputName + ".mdb";
                if (File.Exists(mdb))
                {
                    src.Add(mdb);
                    targ.Add(mdb.FileName);
                }
            }

            if (proj.GenerateSilverlightManifest)
            {
                src.Add(conf.OutputDirectory.Combine("AppManifest.xaml"));
                targ.Add("AppManifest.xaml");
            }

            foreach (ProjectFile pf in proj.Files)
            {
                if (pf.BuildAction == BuildAction.Content)
                {
                    src.Add(pf.FilePath);
                    targ.Add(pf.ProjectVirtualPath);
                }
            }

            BuildResult res = new BuildResult();

            // The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles.
            // Instead we need to iterate over the refs and handle them manually.
            foreach (ProjectReference pr in proj.References)
            {
                if (pr.LocalCopy)
                {
                    var pk = pr.Package;
                    if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith("-redist"))
                    {
                        string err = pr.ValidationErrorMessage;
                        if (!String.IsNullOrEmpty(err))
                        {
                            string msg = String.Format("Could not add reference '{0}' to '{1}': {2}",
                                                       pr.Reference, xapName.FileName, err);
                            res.AddError(msg);
                            monitor.Log.WriteLine(msg);
                            continue;
                        }
                        foreach (string s in pr.GetReferencedFileNames(slnConf))
                        {
                            src.Add(s);
                            targ.Add(Path.GetFileName(s));

                            if (doSdbCopy && s.EndsWith(".dll"))
                            {
                                FilePath mdb = s + ".mdb";
                                if (File.Exists(mdb))
                                {
                                    src.Add(mdb);
                                    targ.Add(mdb.FileName);
                                }
                            }
                        }
                    }
                }
            }

            if (res.ErrorCount > 0)
            {
                res.FailedBuildCount++;
                return(res);
            }

            if (File.Exists(xapName))
            {
                DateTime lastMod    = File.GetLastWriteTime(xapName);
                bool     needsWrite = false;
                foreach (string file in src)
                {
                    if (File.GetLastWriteTime(file) > lastMod)
                    {
                        needsWrite = true;
                        break;
                    }
                }
                if (!needsWrite)
                {
                    return(null);
                }
            }

            monitor.Log.WriteLine("Compressing XAP file...");

            try {
                using (FileStream fs = new FileStream(xapName, FileMode.Create)) {
                    var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs);
                    zipfile.SetLevel(9);

                    byte[] buffer = new byte[4096];

                    for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++)
                    {
                        zipfile.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(targ[i]));
                        using (FileStream inStream = File.OpenRead(src[i])) {
                            int readCount;
                            do
                            {
                                readCount = inStream.Read(buffer, 0, buffer.Length);
                                zipfile.Write(buffer, 0, readCount);
                            } while (readCount > 0);
                        }
                    }
                    if (!monitor.IsCancelRequested)
                    {
                        zipfile.Finish();
                        zipfile.Close();
                    }
                }
            } catch (IOException ex) {
                monitor.ReportError("Error writing xap file.", ex);
                res.AddError("Error writing xap file:" + ex.ToString());
                res.FailedBuildCount++;

                try {
                    if (File.Exists(xapName))
                    {
                        File.Delete(xapName);
                    }
                } catch {}

                return(res);
            }

            if (monitor.IsCancelRequested)
            {
                try {
                    if (File.Exists(xapName))
                    {
                        File.Delete(xapName);
                    }
                } catch {}
            }

            return(res);
        }