Created
July 23, 2015 15:35
-
-
Save Fhernd/51fe0e0a87353da60134 to your computer and use it in GitHub Desktop.
Compresión de archivos en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
using System.IO.Compression; | |
namespace Receta.CSharp.R0523 | |
{ | |
public class UsoGZipStream | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine(Environment.NewLine); | |
// Valida la entrada del usuario: | |
if (args.Length != 1) | |
{ | |
Console.WriteLine("USO: UsoGZipStream.exe [NombreArchivo]"); | |
Console.WriteLine (Environment.NewLine); | |
return; | |
} | |
try | |
{ | |
// Nombre de archivo a comprimir: | |
string nombreArchivo = args[0]; | |
// Validación existencia archivo: | |
if (!File.Exists(nombreArchivo)) | |
{ | |
Console.WriteLine ("El archivo no existe. Intente de nuevo."); | |
Console.WriteLine (Environment.NewLine); | |
return; | |
} | |
using (FileStream fs = File.OpenRead(nombreArchivo)) | |
{ | |
Console.WriteLine ("Tamaño del archivo {0}: {1} bytes.", nombreArchivo, fs.Length.ToString()); | |
ComprimirArchivo(fs); | |
} | |
} | |
catch(Exception ex) | |
{ | |
Console.WriteLine ("Error: El archivo no pudo ser comprimido: {0}", ex.Message); | |
} | |
Console.WriteLine(Environment.NewLine); | |
} | |
private static void ComprimirArchivo(FileStream archivo) | |
{ | |
byte[] bytes = new byte[archivo.Length]; | |
archivo.Read(bytes, 0, (int)archivo.Length); | |
// Comprime el archivo: | |
using(FileStream archivoComprimido = new FileStream(String.Format("{0}.gz", archivo.Name), FileMode.Create)) | |
{ | |
using (GZipStream compresor = new GZipStream(archivoComprimido, CompressionMode.Compress, false)) | |
{ | |
compresor.Write(bytes, 0, bytes.Length); | |
} | |
} | |
// Muestra tamaño del archivo recién comprimido: | |
using(FileStream archivoComprimido = File.OpenRead(String.Format("{0}.gz", archivo.Name))) | |
{ | |
Console.WriteLine("Tamaño del archivo {0}: {1} bytes.", Path.GetFileName(archivoComprimido.Name), archivoComprimido.Length); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment