Agregar archivos de proyecto.

This commit is contained in:
2025-09-19 08:10:08 +02:00
parent c27453cd8a
commit f7e1b035f5
4 changed files with 202 additions and 0 deletions

37
Utilidades.cs Normal file
View File

@@ -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)
{
}
}
}
}

24
tsZip.csproj Normal file
View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<OutputType>Library</OutputType>
<RootNamespace>tsZip</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
<PackageId>tsZip</PackageId>
<PackageTags>netstandard2.0, libreria</PackageTags>
<Version>1.0.1</Version>
<Authors>Manuel</Authors>
<Company>Tecnosis S.A</Company>
<Description>Utilidades de compresión</Description>
<PackageReleaseNotes>
- 2025-09-18 Corrección espacio Nombres
- 2025-09-18 Primera versión
</PackageReleaseNotes>
<!--<PackageReadmeFile>README.md</PackageReadmeFile>-->
</PropertyGroup>
</Project>

25
tsZip.sln Normal file
View File

@@ -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

116
zip.cs Normal file
View File

@@ -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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="ficheroZip">Array de bytes conteniendo el fichero zip.</param>
/// <param name="nombreArchivoDentroZip">Cadena donde se guardará el nombre del fichero que está dentro del fichero zip.</param>
/// <returns>Para que este método funcione correctamente es imprescindible que el archivo zip tenga dentro un único fichero.</returns>
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();
}
/// <summary>
/// Esta función extrae todos los ficheros que haya en un zip y los devuelve como un diccionario.
/// </summary>
/// <param name="ficheroZip">Array de bytes conteniendo el fichero zip.</param>
/// <returns>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.</returns>
public static Dictionary<string, MemoryStream> ExtraerFicherosDeZip(byte[] ficheroZip)
{
var resultado = new Dictionary<string, MemoryStream>();
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<string, byte[]> 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();
}
}
}
}