public static string Decrypt(string encryptedFilePath) { string decryptedFileName = String.Empty; string directoryPath = string.Empty; try { directoryPath = Path.GetDirectoryName(encryptedFilePath); decryptedFileName = Path.GetFileName(encryptedFilePath).Remove(0, "encryptedVersion_".Length); decryptedFileName = Path.Combine(directoryPath, decryptedFileName); // Decrypt the source file and write it to the destination file. using (var sourceStream = File.OpenRead(encryptedFilePath)) using (var destinationStream = File.Create(decryptedFileName)) using (var provider = new AesCryptoServiceProvider()) { var IV = new byte[provider.IV.Length]; sourceStream.Read(IV, 0, IV.Length); using (var cryptoTransform = provider.CreateDecryptor(key_Aes, IV)) using (var cryptoStream = new CryptoStream(sourceStream, cryptoTransform, CryptoStreamMode.Read)) { cryptoStream.CopyTo(destinationStream); } } } catch (Exception ex) { UserInteraction.ErrorMsg(); UserInteraction.PrintExceptionInfo(ex); } return(decryptedFileName); }
public static string Encrypt(string sourceFileName) { string destinationFileName = string.Empty; string encryptedFileName = "encryptedVersion_" + Path.GetFileName(sourceFileName); // Full path of encrypted file. destinationFileName = Path.Combine(Path.GetDirectoryName(sourceFileName), encryptedFileName); try { using (var sourceStream = File.OpenRead(sourceFileName)) using (var destinationStream = File.Create(destinationFileName)) using (var provider = new AesCryptoServiceProvider()) using (var cryptoTransform = provider.CreateEncryptor()) using (var cryptoStream = new CryptoStream(destinationStream, cryptoTransform, CryptoStreamMode.Write)) { // Save the IV to the file for decryption. destinationStream.Write(provider.IV, 0, provider.IV.Length); sourceStream.CopyTo(cryptoStream); key_Aes = provider.Key; } } catch (Exception ex) { UserInteraction.ErrorMsg(); UserInteraction.PrintExceptionInfo(ex); } return(destinationFileName); }
// 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); }
// 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); }
// 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(); }
// Пока что полностью не нужные методы ... public static void CheckSourceDir(string sourceDirPath, string targetDirectoryPath) { List <string> existedFiles; List <string> newFiles; //List<string> newCompressedFiles; // Stores names of files after compressing. try { existedFiles = new List <string>(); newFiles = new List <string>(); //newCompressedFiles = new List<string>(); DirectoryInfo dirInfo = new DirectoryInfo(sourceDirPath); ProcessDirectoriesForNewFiles(dirInfo, newFiles, existedFiles); // Processing all new files. foreach (var newFile in newFiles) { // Encryption logic.... var encryptedFileName = Encrypt(newFile); // Compress... Compress(encryptedFileName); //newCompressedFiles.Add(GetZipArchiveName(encryptedFileName)); // Move archive file to "TargetDirectory"... var movedFile = MoveFileOrFolder(encryptedFileName, targetDirectoryPath); // Decompress... DecompressGZip(movedFile); // DeEncryption... Decrypt(movedFile); } // Update existed files. existedFiles.AddRange(newFiles); } catch (Exception ex) { UserInteraction.ErrorMsg(); UserInteraction.PrintExceptionInfo(ex); } WriteLine(); }
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(); }
// 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(); }
// Renames according pattern - "Sales_YYYY_MM_DD_HH_mm_SS.txt" public static string RenameBuisnessFile(string sourceFilePath) { string childDirectory = Path.GetDirectoryName(sourceFilePath); string newFilePath = string.Empty; try { FileInfo ourFile = new FileInfo(sourceFilePath); DateTime creationTime = ourFile.CreationTime; string newFileName = $"Q_{creationTime.Year}_{creationTime.Month}_{creationTime.Day}_{creationTime.Hour}_" + $"{creationTime.Minute}_{creationTime.Second}.txt"; // Строим директорию относительно вермени создания файла. childDirectory = Path.Combine(childDirectory, $"{creationTime.Year}"); childDirectory = Path.Combine(childDirectory, $"{creationTime.Month}"); childDirectory = Path.Combine(childDirectory, $"{creationTime.Day}"); if (!Directory.Exists(childDirectory)) { Directory.CreateDirectory(childDirectory); } newFilePath = Path.Combine(childDirectory, newFileName); // Chenges name of file if need. newFilePath = GetUniqueFileName(newFilePath); RenameFile(sourceFilePath, newFilePath); } catch (Exception ex) { UserInteraction.ErrorMsg(); UserInteraction.PrintExceptionInfo(ex); } return(newFilePath); }