Skip to content

Instantly share code, notes, and snippets.

@olecksamdr
Last active September 29, 2016 10:01
Show Gist options
  • Save olecksamdr/7c1cc829b247f5334cb27354f2dfff7d to your computer and use it in GitHub Desktop.
Save olecksamdr/7c1cc829b247f5334cb27354f2dfff7d to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Compression;
namespace Compression
{
class MyCompression
{
static string removeExt(string str) {
Regex rgx = new Regex(@"\.\w+$");
return rgx.Replace(str, "");
}
static bool isCompressed(string filename) {
int last = filename.Length;
string ext = filename.Substring(last - 3, 3);
if (ext == ".gz") return true;
else return false;
}
static void Compress(string filePath) {
string arhivePath = filePath + ".gz";
GZipStream compStream = new GZipStream( File.Create(arhivePath) , CompressionMode.Compress);
FileStream file = new FileStream(filePath, FileMode.Open);
int theByte = file.ReadByte();
while ( theByte != -1) {
compStream.WriteByte(Convert.ToByte(theByte));
theByte = file.ReadByte();
}
compStream.Dispose();
file.Close();
}
static void Uncompress(string arhivePath) {
string filename = removeExt(arhivePath);
GZipStream arhive = new GZipStream( File.Create(arhivePath) , CompressionMode.Decompress);
FileStream uncompressedFile = new FileStream(filename, FileMode.Open);
int theByte = arhive.ReadByte();
while ( theByte != -1) {
uncompressedFile.WriteByte(Convert.ToByte(theByte));
theByte = arhive.ReadByte();
}
uncompressedFile.Close();
arhive.Dispose();
arhive.Close();
}
static void Main(string[] args) {
string file;
if (args.Length < 1) {
Console.WriteLine("no argument passed.\n Use compress.exe pathToSourceFile");
} else {
file = args[0];
if (isCompressed(file)) {
Uncompress(file);
} else {
Compress(file);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment