Example #1
0
        private void WriteHeader()
        {
            Header header = new Header
            {
                Root         = this.Root,
                NextPosition = this.LastPosition,
                Order        = this.Order
            };

            using (var fs = new FileStream(this.Path, FileMode.OpenOrCreate))
            {
                fs.Seek(0, SeekOrigin.Begin);
                fs.Write(ByteGenerator.ConvertToBytes(header.ToFixedSizeString()), 0, header.FixedSizeText);
            }
        }
Example #2
0
        public async Task <IActionResult> DecompressFile([FromForm] IFormFile file)
        {
            try
            {
                // Escribir archivo subido hacia el servidor para trabajar con ese
                var path = _env.ContentRootPath;
                path = Path.Combine(path, "Files");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string pathInfo = Path.Combine(path, "Info");
                if (!Directory.Exists(pathInfo))
                {
                    Directory.CreateDirectory(pathInfo);
                }

                if (System.IO.File.Exists($"{pathInfo}/archivoCargado.txt"))
                {
                    System.IO.File.Delete($"{pathInfo}/archivoCargado.txt");
                }

                using var saver = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                await file.CopyToAsync(saver);

                saver.Close();

                // Leer el archivo en el servidor para trabajar sobre él
                using var fileWritten = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                using var reader      = new BinaryReader(fileWritten);
                var buffer = new byte[2000000];
                while (fileWritten.Position < fileWritten.Length)
                {
                    buffer = reader.ReadBytes(2000000);
                }
                reader.Close();
                fileWritten.Close();

                var nodeString = ByteGenerator.ConvertToString(buffer);

                Huffman huff = new Huffman();
                string  cadena_descifrada = huff.Descifrado(nodeString);


                // Buscar el nombre original en el archivo Historial.txt
                string pathHistorial = Path.Combine(pathInfo, "Historial.txt");
                if (!System.IO.File.Exists(pathHistorial))
                {
                    return(StatusCode(500, "Internal server error"));
                }
                string cadenaHistorial = System.IO.File.ReadAllText(pathHistorial);

                string[] cadenas        = cadenaHistorial.Split('/');
                string   nombreOriginal = "";

                foreach (var item in cadenas)
                {
                    if (item.Contains(file.FileName))
                    {
                        string[] valores = item.Split(';');
                        nombreOriginal = valores[0].Substring(0, valores[0].Length - 4);
                        break;
                    }
                }

                // Escribir el archivo {original}.txt en el servidor
                using (var fs = new FileStream($"{path}/{nombreOriginal}.txt", FileMode.OpenOrCreate))
                {
                    fs.Write(ByteGenerator.ConvertToBytes(cadena_descifrada), 0, cadena_descifrada.Length);
                }

                // Archivo a mandar de regreso
                //var fileStream = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                //return File(fileStream, "text/plain");

                return(Ok());
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Internal server error"));
            }
        }
        public async Task <IActionResult> CompressFile([FromForm] IFormFile file, string name)
        {
            try
            {
                // Escribir archivo subido hacia el servidor para trabajar con ese
                var path = _env.ContentRootPath;
                path = Path.Combine(path, "Files");

                string pathInfo = Path.Combine(path, "Info");


                if (System.IO.File.Exists($"{pathInfo}/archivoCargado.txt"))
                {
                    System.IO.File.Delete($"{pathInfo}/archivoCargado.txt");
                }

                using var saver = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                await file.CopyToAsync(saver);

                saver.Close();


                // Leer el archivo en el servidor para trabajar sobre él
                using var fileWritten = new FileStream($"{pathInfo}/archivoCargado.txt", FileMode.OpenOrCreate);
                using var reader      = new BinaryReader(fileWritten);
                var buffer = new byte[2000000];
                while (fileWritten.Position < fileWritten.Length)
                {
                    buffer = reader.ReadBytes(2000000);
                }
                reader.Close();
                fileWritten.Close();

                var nodeString = ByteGenerator.ConvertToString(buffer);

                Huffman huff           = new Huffman();
                string  cadena_cifrada = huff.Cifrado(nodeString);


                // Escribir el archivo {name}.huff en el servidor

                using (var fs = new FileStream($"{path}/{name}.huff", FileMode.OpenOrCreate))
                {
                    fs.Write(ByteGenerator.ConvertToBytes(cadena_cifrada), 0, cadena_cifrada.Length);
                }


                // Obtener la info de compresión
                CompressionInfo cInfo = new CompressionInfo();
                cInfo.originalName        = file.FileName;
                cInfo.compressedFilePath  = Path.Combine(path, $"{name}.huff");
                cInfo.compressionRatio    = Math.Round(Convert.ToDouble(cadena_cifrada.Length) / Convert.ToDouble(nodeString.Length), 2);
                cInfo.compressionFactor   = Math.Round(1 / cInfo.compressionRatio, 2);
                cInfo.reductionPercentage = Math.Round((1 - cInfo.compressionRatio) * 100, 2);


                // Escribir en el archivo Historial.txt
                string       pathHistorial   = Path.Combine(pathInfo, "Historial.txt");
                string       cadenaHistorial = System.IO.File.ReadAllText(pathHistorial);
                StreamWriter newfile         = new StreamWriter(pathHistorial);

                if (cadenaHistorial.Length != 0)
                {
                    newfile.Write(cadenaHistorial);
                    newfile.Write("/");
                }
                newfile.Write(cInfo.originalName + ";" + cInfo.compressedFilePath + ";" + (cInfo.compressionRatio).ToString() + ";" + (cInfo.compressionFactor).ToString() + ";" + (cInfo.reductionPercentage).ToString());

                newfile.Close();


                //Archivo a mandar de regreso
                //var fileStream = new FileStream($"{path}/{name}.huff", FileMode.OpenOrCreate);
                string mensaje = "Archivo comprimido exitosamente";
                return(Ok(new { mensaje }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, "Internal server error"));
            }
        }
Example #4
0
        public void DecodeFile(byte[] text, string newName, string name)
        {
            string txt = ByteGenerator.ConvertToString(text);

            string[] separadores = { "@@@" };
            string[] nodes       = txt.Split(separadores, StringSplitOptions.None);

            int start = (nodes.Length - 1) * 3;

            Dictionary <byte, int> freq = new Dictionary <byte, int>();

            for (int i = 0; i < nodes.Length - 1; i++)
            {
                string val = nodes[i];

                string character = "";
                string integer   = "";

                if (int.TryParse(val[0].ToString(), out _))
                {
                    character += val[0];
                    for (int j = 1; j < val.Length; j++)
                    {
                        integer += val[j];
                        start++;
                    }
                }
                else
                {
                    for (int j = 0; j < val.Length; j++)
                    {
                        if (!int.TryParse(val[j].ToString(), out _))
                        {
                            character += val[j];
                        }
                        else
                        {
                            integer += val[j];
                            start++;
                        }
                    }
                }

                byte[] bt;
                if (character == "NTR")
                {
                    bt = ByteGenerator.ConvertToBytes('\n'.ToString());
                }
                else if (character == "NDL")
                {
                    bt = ByteGenerator.ConvertToBytes('\r'.ToString());
                }
                else
                {
                    bt = ByteGenerator.ConvertToBytes(character.ToString());
                }
                start += character.Length;

                if (!freq.ContainsKey(bt[0]))
                {
                    freq.Add(bt[0], Convert.ToInt32(integer));
                }
            }

            BuildHuffman(freq);

            BitArray result  = ToBitArray(text.Skip(start).ToArray());
            int      index   = -1;
            string   decoded = "";

            while (index < result.Length - 1)
            {
                decode(this.root, ref index, result, ref decoded);
            }

            string basePath = string.Format(@"{0}Arboles\", AppContext.BaseDirectory);
            string fullPath = basePath + newName;

            using (StreamWriter sw = new StreamWriter(fullPath))
            {
                sw.Write(decoded);
            }
        }