Esempio n. 1
0
        public static string RenameFile(string filePath, string newFileName)
        {
            var newFilePath = Path.Combine(GetDirectoryFromFileOrFolderPath(filePath), newFileName);

            if (!File.Exists(filePath))
            {
                WriteLine($"Such file \"{filePath}\" doesn't exists ! \n");
            }
            else if (File.Exists(newFilePath))
            {
                WriteLine($"Such file \"{newFileName}\" already exists ! \n");
            }
            else
            {
                try
                {
                    File.Move(filePath, newFilePath);
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                }
                finally
                {
                    //WriteLine();
                }
            }

            return(newFilePath);
        }
Esempio n. 2
0
        public static void RenameFolder(string dirPath)
        {
            Write("Enter new folder name : ");

            var newFolderName = GetFolderName();
            var newFolderPath = Path.Combine(GetDirectoryFromFileOrFolderPath(dirPath), newFolderName);

            if (!Directory.Exists(dirPath))
            {
                WriteLine($"Such folder \"{dirPath}\" doesn't exists ! \n");
            }
            else if (Directory.Exists(newFolderPath))
            {
                WriteLine($"Such folder \"{newFolderName}\" already exists ! \n");
            }
            else
            {
                try
                {
                    Directory.Move(dirPath, newFolderPath);
                    WriteLine("Folder renamed successfully ! ");
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                }
                finally
                {
                    WriteLine();
                }
            }
        }
Esempio n. 3
0
        // Creates new Directory and deletes old with the same name.
        public static string CreateDirectory(string path)
        {
            string ourPath = path;

            if (Directory.Exists(path))
            {
                WriteLine($"Folder wasn't created !");
                WriteLine($"Folder {path} is already exists ! \n");
            }
            else
            {
                try
                {
                    DirectoryInfo dInfo = Directory.CreateDirectory(path);

                    WriteLine($"Directory \"{path}\" was successfully created ! \n");
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                    return(ourPath);
                }
            }
            return(ourPath);
        }
Esempio n. 4
0
        // Checks if such drive exists, will it work for other OS?
        private static bool DriveExists(string driveName)
        {
            bool answ = false;

            driveName += @":\";

            try
            {
                DriveInfo[] drives = DriveInfo.GetDrives();

                foreach (DriveInfo drive in drives)
                {
                    if (driveName == drive.Name)
                    {
                        answ = true;
                    }
                }
            }
            catch (Exception ex)
            {
                UserInteraction.PrintExceptionInfo(ex);
            }

            return(answ);
        }
Esempio n. 5
0
        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);
        }
Esempio n. 6
0
        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);
        }
Esempio n. 7
0
        // Creates new file and deletes old with the same name.
        public static void CreateFile(string path)
        {
            if (File.Exists(path))
            {
                WriteLine($"File wasn't created !");
                WriteLine($"File {path} is already exists ! \n");
            }
            else
            {
                try
                {
                    // We are using "using" cuz "File.Create()" returns stream and doesn't close it.
                    using (FileStream fs = File.Create(path))
                    {
                    }

                    WriteLine($"File \"{path}\" was successfully created ! \n");
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                    return;
                }
            }
        }
Esempio n. 8
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. 9
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. 10
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. 11
0
        // Пока что полностью не нужные методы ...
        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();
        }
Esempio n. 12
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. 13
0
        // Returns new file name.
        public static string MoveFileOrFolder(string currentDirPath, string newDirPath)
        {
            var supposedNewPath = string.Empty;

            try
            {
                supposedNewPath = Path.Combine(newDirPath, GetFileOrFolderNameFromPath(currentDirPath));
            }
            catch (Exception ex)
            {
                UserInteraction.PrintExceptionInfo(ex);
                return(supposedNewPath);
            }

            if (!File.Exists(currentDirPath) && !Directory.Exists(currentDirPath))
            {
                WriteLine($"Such file or folder \"{currentDirPath}\" doesn't exists ! ");
            }
            else if (!Directory.Exists(newDirPath))
            {
                WriteLine($"Such file or folder \"{newDirPath}\" doesn't exists ! ");
            }
            else if (File.Exists(supposedNewPath) || Directory.Exists(supposedNewPath))
            {
                WriteLine($"Such file or directory \"{supposedNewPath}\" already exists ! ");
            }
            else
            {
                try
                {
                    Directory.Move(currentDirPath, supposedNewPath);
                    WriteLine("Move successfully ! ");
                }
                catch (Exception ex)
                {
                    UserInteraction.PrintExceptionInfo(ex);
                }
            }

            WriteLine();

            return(supposedNewPath);
        }
Esempio n. 14
0
 public static void DeleteFile(string path)
 {
     if (File.Exists(path))
     {
         try
         {
             File.Delete(path);
             WriteLine($"File \"{path}\" was successfully deleted ! \n");
         }
         catch (Exception ex)
         {
             UserInteraction.PrintExceptionInfo(ex);
             return;
         }
     }
     else
     {
         WriteLine($"File hasn't been deleted !");
         WriteLine($"File \"{path}\" doesn't exists ! \n");
     }
 }
Esempio n. 15
0
 public static void DeleteDirectory(string path)
 {
     if (Directory.Exists(path))
     {
         try
         {
             Directory.Delete(path);
             WriteLine($"Directory \"{path}\" was successfully deleted ! \n");
         }
         catch (Exception ex)
         {
             UserInteraction.PrintExceptionInfo(ex);
             return;
         }
     }
     else
     {
         WriteLine($"Folder hasn't been deleted !");
         WriteLine($"Folder \"{path}\" doesn't exists ! \n");
     }
 }
Esempio n. 16
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();
        }
Esempio n. 17
0
        // 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);
        }
Esempio n. 18
0
        private static string[] GetAllDirectories()
        {
            List <string> ourDirectories = new List <string>();

            try
            {
                DriveInfo[] drives = DriveInfo.GetDrives();

                foreach (DriveInfo drive in drives)
                {
                    var partOfDirectories = GetAllDirectories(drive.Name);

                    // Add our "partOfFiles" list to the original "ourFiles" list.
                    ourDirectories.AddRange(partOfDirectories);
                }
            }
            catch (Exception ex)
            {
                UserInteraction.PrintExceptionInfo(ex);
            }

            return(ourDirectories.ToArray());
        }