Esempio n. 1
0
        // Returns path of decompressed file.
        // "path" - Path of compressed file or folder.
        // Typically : Path.ChangeExtension(dirPath, ".gz").
        // dirPath - source filepath.
        public static string DecompressGZip(string path)
        {
            string directoryOfPath          = Path.GetDirectoryName(path);
            string fileOrFolderNameFromPath = Path.GetFileNameWithoutExtension(path);
            string newFileOrFolderNameFromPath;
            string destinationPath = String.Empty;

            try
            {
                newFileOrFolderNameFromPath = fileOrFolderNameFromPath + ".txt"; // А что если я заранеее не знаю какого расширения
                // "destinationPath" - path to the decompressed file or directory.
                destinationPath = Path.Combine(directoryOfPath, newFileOrFolderNameFromPath);

                if (File.Exists(destinationPath) || Directory.Exists(destinationPath))
                {
                    throw new Exception($"Such file or directory {destinationPath} is already exists !");
                }
                else
                {
                    // Проверяем существует ли файл котрый мы хотим распаковать. Прим : "fileOrFolder.gz".
                    if (File.Exists(path))
                    {
                        // Логика распаковки файла\директории ....................

                        // поток для чтения из сжатого файла
                        using (FileStream sourceStream = new FileStream(path, FileMode.OpenOrCreate))
                        {
                            // поток для записи восстановленного файла
                            using (FileStream targetStream = File.Create(destinationPath))
                            {
                                // поток разархивации
                                using (GZipStream decompressionStream = new GZipStream(sourceStream, CompressionMode.Decompress))
                                {
                                    decompressionStream.CopyTo(targetStream);
                                    //Console.WriteLine("Восстановлен файл: {0}", newFileOrFolderNameFromPath);
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception($"Such Directory or file {path} doesn't exists ! ");
                    }
                }

                UserInteraction.SuccessMsg();
                //WriteLine($"Compressed file : {destinationPath} !");
            }
            catch (Exception ex)
            {
                UserInteraction.ErrorMsg();
                UserInteraction.PrintExceptionInfo(ex);
            }

            //WriteLine();
            return(destinationPath);
        }
Esempio n. 2
0
        // Returns new file name.
        // Path to the file or folder we want to compress.
        // Compresses to ".gz" format.
        public static string Compress(string path)
        {
            string directoryOfPath          = GetDirectoryFromFileOrFolderPath(path);
            string fileOrFolderNameFromPath = GetFileOrFolderNameFromPath(path);
            string newFileOrFolderNameFromPath;
            string destinationPath = string.Empty;

            try
            {
                newFileOrFolderNameFromPath = Path.ChangeExtension(fileOrFolderNameFromPath, ".gz");
                destinationPath             = Path.Combine(directoryOfPath, newFileOrFolderNameFromPath);

                // Process will depend on is it file or directory.
                if (File.Exists(path))
                {
                    // поток для чтения исходного файла
                    using (FileStream sourceStream = new FileStream(path, FileMode.Open))
                    {
                        // поток для записи сжатого файла
                        using (FileStream targetStream = File.Create(destinationPath))
                        {
                            // поток архивации
                            using (GZipStream compressionStream = new GZipStream(targetStream, CompressionMode.Compress))
                            {
                                // копируем байты из одного потока в другой
                                sourceStream.CopyTo(compressionStream);
                                WriteLine("Сжатие файла {0} завершено. Исходный размер: {1}  сжатый размер: {2}.",
                                          path, sourceStream.Length.ToString(), targetStream.Length.ToString());
                            }
                        }
                    }
                }
                else if (Directory.Exists(path))
                {
                    ZipFile.CreateFromDirectory(path, destinationPath);
                }
                else
                {
                    throw new Exception($"Such Directory or file {path} doesn't exists ! ");
                }


                UserInteraction.SuccessMsg();
                WriteLine($"Compressed file : {destinationPath} !");
            }
            catch (Exception ex)
            {
                UserInteraction.ErrorMsg();
                UserInteraction.PrintExceptionInfo(ex);
            }

            WriteLine();
            return(destinationPath);
        }
Esempio n. 3
0
        // Write text to the end of file (doesn't rewrite it).
        public static void WriteToFile(string fileName)
        {
            FileInfo file;

            try
            {
                file = new FileInfo(fileName);
            }
            catch (Exception ex)
            {
                UserInteraction.PrintExceptionInfo(ex);
                WriteLine();
                return;
            }

            if (!file.Exists)
            {
                UserInteraction.ErrorMsg();
                WriteLine($"File {fileName} doesn't exists !");
            }
            else if (file.Extension != ".txt")
            {
                UserInteraction.ErrorMsg();
                WriteLine($"File {fileName} should be an .txt file !");
            }
            else
            {
                Write("Input text (for writing to file) : ");
                var userText = ReadLine();

                try
                {
                    using (StreamWriter sw = new StreamWriter(fileName, true, System.Text.Encoding.Default))
                    {
                        sw.WriteLineAsync(userText);
                    }

                    UserInteraction.SuccessMsg();
                    WriteLine("Recording completed !");
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                }
            }

            WriteLine();
        }
Esempio n. 4
0
        public static void ReadTextFromFile(string filePath)
        {
            string   stringFromFile = string.Empty;
            FileInfo file;

            try
            {
                file = new FileInfo(filePath);
            }
            catch (Exception ex)
            {
                UserInteraction.ErrorMsg();
                UserInteraction.PrintExceptionInfo(ex);
                WriteLine();
                return;
            }

            if (!file.Exists)
            {
                UserInteraction.ErrorMsg();
                UserInteraction.FileNotExistsMsg(file.FullName);
            }
            else
            {
                try
                {
                    using (StreamReader sr = new StreamReader(file.FullName))
                    {
                        stringFromFile = sr.ReadToEnd();
                    }

                    UserInteraction.SuccessMsg();
                    WriteLine("Text from file : ");
                    WriteLine(stringFromFile);
                }
                catch (Exception ex)
                {
                    UserInteraction.ErrorMsg();
                    UserInteraction.PrintExceptionInfo(ex);
                }
            }

            WriteLine();
        }
Esempio n. 5
0
        // Path of compressed file or folder.
        // Typically : Path.ChangeExtension(dirPath, ".zip").
        // dirPath - source filepath.
        public static void DecompressZip(string path)
        {
            string directoryOfPath          = GetDirectoryFromFileOrFolderPath(path);
            string fileOrFolderNameFromPath = GetFileOrFolderNameFromPath(path);
            string newFileOrFolderNameFromPath;
            string destinationPath;

            try
            {
                newFileOrFolderNameFromPath = Path.ChangeExtension(fileOrFolderNameFromPath, null);
                destinationPath             = Path.Combine(directoryOfPath, newFileOrFolderNameFromPath);

                if (Directory.Exists(destinationPath) || File.Exists(destinationPath))
                {
                    throw new Exception($"Such file or directory {destinationPath} is already exists !");
                }
                else
                {
                    if (File.Exists(path))
                    {
                        Directory.CreateDirectory(destinationPath);
                        ZipFile.ExtractToDirectory(path, destinationPath);
                    }
                    else
                    {
                        throw new Exception($"Such Directory or file {path} doesn't exists ! ");
                    }
                }

                UserInteraction.SuccessMsg();
                WriteLine($"Decompressed file : {destinationPath} !");
            }
            catch (Exception ex)
            {
                UserInteraction.ErrorMsg();
                UserInteraction.PrintExceptionInfo(ex);
            }

            WriteLine();
        }