diff --git a/Utilidades.cs b/Utilidades.cs new file mode 100644 index 0000000..c7161bb --- /dev/null +++ b/Utilidades.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Text.RegularExpressions; +using System.Xml; +using System.Xml.Serialization; + + + public class Utilidades + { + public static void CreaEstructuraDirectorio(string Ruta) + { + string[] sDirectorios = Ruta.Split('\\'); + string sDirectorio = ""; + int i; + var loopTo = sDirectorios.Length - 1; + for (i = 0; i <= loopTo; i++) + { + try + { + sDirectorio += sDirectorios[i] + @"\"; + if (!Directory.Exists(sDirectorio)) + Directory.CreateDirectory(sDirectorio); + } + catch (Exception ex) + { + } + } + } + } diff --git a/tsZip.csproj b/tsZip.csproj new file mode 100644 index 0000000..61e8150 --- /dev/null +++ b/tsZip.csproj @@ -0,0 +1,24 @@ + + + + netstandard2.0 + + + + Library + tsZip + netstandard2.0 + tsZip + netstandard2.0, libreria + 1.0.1 + Manuel + Tecnosis S.A + Utilidades de compresión + + - 2025-09-18 Corrección espacio Nombres + - 2025-09-18 Primera versión + + + + + diff --git a/tsZip.sln b/tsZip.sln new file mode 100644 index 0000000..a730699 --- /dev/null +++ b/tsZip.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.14.36511.14 d17.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "tsZip", "tsZip.csproj", "{DA86E6B5-98EC-4C64-A080-9057E5C6CD72}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DA86E6B5-98EC-4C64-A080-9057E5C6CD72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DA86E6B5-98EC-4C64-A080-9057E5C6CD72}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DA86E6B5-98EC-4C64-A080-9057E5C6CD72}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DA86E6B5-98EC-4C64-A080-9057E5C6CD72}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {276534D1-5A97-4BD5-8CCB-42DB68E8A5B8} + EndGlobalSection +EndGlobal diff --git a/zip.cs b/zip.cs new file mode 100644 index 0000000..8c9471c --- /dev/null +++ b/zip.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; + +namespace tsZip +{ + + public class Zip + { + public static void ExtraeTodoDeZip(MemoryStream FicheroZIP, string RutaDestino, bool EliminaDirectorioDestino = false) + { + if (RutaDestino.EndsWith(@"\") == false) + RutaDestino += @"\"; + if (Directory.Exists(RutaDestino) & EliminaDirectorioDestino) + { + Directory.Delete(RutaDestino, true); + } + if (!Directory.Exists(RutaDestino)) + Utilidades.CreaEstructuraDirectorio(RutaDestino); + var fzip = new ZipArchive(FicheroZIP, ZipArchiveMode.Read); + foreach (var entry in fzip.Entries) + { + string sDestino = RutaDestino + entry.FullName.Replace("/", @"\"); + if (!Directory.Exists(Path.GetDirectoryName(sDestino))) + { + Utilidades.CreaEstructuraDirectorio(Path.GetDirectoryName(sDestino)); + } + if (entry.FullName.EndsWith("/") == false) + entry.ExtractToFile(sDestino); + } + } + /// + /// Esta función extrae el único fichero que hay dentro de un fichero zip, lo devuelve como array de bytes como retorno de la función, e indica su nombre en un parámetro por referencia. + /// + /// Array de bytes conteniendo el fichero zip. + /// Cadena donde se guardará el nombre del fichero que está dentro del fichero zip. + /// Para que este método funcione correctamente es imprescindible que el archivo zip tenga dentro un único fichero. + public static byte[] ExtraerFicheroUnicoDeZip(byte[] ficheroZip, ref string nombreArchivoDentroZip) + { + Stream sFichero; + var za = new ZipArchive(new MemoryStream(ficheroZip)); + if (za.Entries.Count == 1) + { + nombreArchivoDentroZip = za.Entries.First().Name; + sFichero = za.Entries.First().Open(); + } + else + { + throw new Exception("Se esperaba que el archivo zip tuviera un único fichero dentro, pero la cantidad es distinta. Se aborta la operación."); + } + + var ms = new MemoryStream(); + sFichero.CopyTo(ms); + sFichero.Dispose(); + + return ms.ToArray(); + } + /// + /// Esta función extrae todos los ficheros que haya en un zip y los devuelve como un diccionario. + /// + /// Array de bytes conteniendo el fichero zip. + /// Como todo es en memoria, hay que tener cuidado de que los ficheros extraídos quepan en memoria adecuadamente, teniendo en cuenta las posibles restricciones de memoria que el sistema operativo pueda tener para procesos individuales. + public static Dictionary ExtraerFicherosDeZip(byte[] ficheroZip) + { + var resultado = new Dictionary(); + var za = new ZipArchive(new MemoryStream(ficheroZip)); + foreach (var e in za.Entries) + resultado.Add(e.FullName, (MemoryStream)e.Open()); + return resultado; + } + + // Shared Function ComprimeStream(streamAComprimir As IO.Stream, NombreFicheroAcomprimir As String) As IO.MemoryStream + // Dim ms As New IO.MemoryStream + + // Dim fzip As New ZipArchive(ms, ZipArchiveMode.Create) + // Dim entry As ZipArchiveEntry = fzip.CreateEntryFromFile(NombreFicheroAcomprimir, streamAComprimir) + // Dim entry As ZipArchiveEntry = fzip.CreateEntry((NombreFicheroAcomprimir, streamAComprimir) + // End Function + + // Public Shared Function ComprimirArchivos(dArchivos As Dictionary(Of String, Byte())) As Byte() ' NO ESTÁ PROBADA + // Dim ms As New MemoryStream + // Dim za As New ZipArchive(ms, ZipArchiveMode.Create, True) + // For Each f In dArchivos + // Dim nf = za.CreateEntry(f.Key) + // Dim es = nf.Open + // Dim msa As New MemoryStream(f.Value) + // msa.CopyTo(es) + // es.Close() + // Next + // Return ms.ToArray + // End Function + public static byte[] ComprimirArchivos(Dictionary fileContents) + { + using (var memoryStream = new MemoryStream()) + { + using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) + { + foreach (var entry in fileContents) + { + string fileName = entry.Key; + byte[] fileData = entry.Value; + var zipEntry = archive.CreateEntry(fileName); + + using (var entryStream = zipEntry.Open()) + { + entryStream.Write(fileData, 0, fileData.Length); + } + } + } + return memoryStream.ToArray(); + } + } + } +} \ No newline at end of file