예제 #1
0
        static bool CopyDirectory(string sourceDirName, string destDirName)
        {
            try
            {
                DirectoryInfo   dir  = new DirectoryInfo(sourceDirName);
                DirectoryInfo[] dirs = dir.GetDirectories();

                if (!Directory.Exists(destDirName))
                {
                    Directory.CreateDirectory(destDirName);
                }

                FileInfo[] files = dir.GetFiles();
                foreach (FileInfo file in files)
                {
                    string temppath = Path.Combine(destDirName, file.Name);
                    file.CopyTo(temppath, true);
                    ConsoleDrawings.PrintInformation($"Копируем {file.Name}");
                }

                foreach (DirectoryInfo subdir in dirs)
                {
                    string temppath = Path.Combine(destDirName, subdir.Name);
                    CopyDirectory(subdir.FullName, temppath);
                }
                return(true);
            }
            catch (Exception e)
            {
                ConsoleDrawings.PrintError($"Ошибка копирования: {e.Message}");
                return(false);
            }
        }
예제 #2
0
 static void FILECommand(List <string> arguments)
 {
     if (arguments.Count == 0)
     {
         ConsoleDrawings.PrintError("Неверные параметры...");
         return;
     }
     else if (arguments.Count == 1)
     {
         if (arguments[0].Trim() == "/?")
         {
             ConsoleDrawings.PrintInformation("file <путь к файлу, который необходимо вывести>");
         }
         else
         {
             ReadFile(arguments[0]);
         }
     }
     else
     {
         string resPath = arguments[0];
         for (int i = 1; i < arguments.Count; i++)
         {
             resPath += " ";
             resPath += arguments[i];
         }
         resPath = resPath.Trim();
         ReadFile(resPath);
     }
 }
예제 #3
0
 static void RMCommand(List <string> arguments)
 {
     if (arguments.Count == 0)
     {
         ConsoleDrawings.PrintError("Неверные параметры...");
         return;
     }
     else if (arguments.Count == 1)
     {
         if (arguments[0].Trim() == "/?")
         {
             ConsoleDrawings.PrintInformation("rm <путь к папке/файлу, которую/который необходимо удалить>");
         }
         else
         {
             Delete(arguments[0]);
         }
     }
     else
     {
         string resPath = arguments[0];
         for (int i = 1; i < arguments.Count; i++)
         {
             resPath += " ";
             resPath += arguments[i];
         }
         resPath = resPath.Trim();
         Delete(resPath);
     }
 }
예제 #4
0
        //Если в параметрах существует путь с пробелом, то нужно сначала разобрать пути, потому запускать копирование
        //поэтому вынес непосредственно копирование в отдельную процедуру
        static void Copy(string source, string dest)
        {
            try
            {
                FileAttributes attr = File.GetAttributes(source);

                if (attr.HasFlag(FileAttributes.Directory))
                {
                    if (CopyDirectory(source, dest))
                    {
                        ConsoleDrawings.PrintInformation("Копирование завершено...");
                    }
                }
                else
                {
                    try
                    {
                        File.Copy(source, dest, true);
                        ConsoleDrawings.PrintInformation("Копирование завершено...");
                    }
                    catch (Exception e)
                    {
                        ConsoleDrawings.PrintError($"Ошибка копирования: {e.Message}");
                    }
                }
            }
            catch (Exception e)
            {
                ConsoleDrawings.PrintError(e.Message);
            }
        }
 public static void PrintMainPanelHeader(string header)
 {
     Console.ForegroundColor = frameForegroundColor;
     Console.BackgroundColor = frameBackgroundColor;
     Console.SetCursorPosition(0, 0);
     Console.Write(DoubleLinesToPrint.TopLeft);
     Console.Write(new string(DoubleLinesToPrint.LineX[0],
                              Configuration.ConsoleWidth - 2));
     Console.Write(DoubleLinesToPrint.TopRight);
     ConsoleDrawings.PrintString(header, Configuration.ConsoleWidth / 2 - header.Length / 2, 0);
     Console.ForegroundColor = ConsoleColor.White;
     Console.BackgroundColor = ConsoleColor.Black;
 }
예제 #6
0
        static void SetCurrentPath(string path)
        {
            if (!Directory.Exists(path))
            {
                ConsoleDrawings.PrintError("Указанная директория не существует");
                _currentPath = "";
                CurrentFoldersFiles.Clear();
                return;
            }
            _currentPath = path;
            if (CurrentFoldersFiles.Count != 0)
            {
                CurrentFoldersFiles.Clear();
            }

            try
            {
                string[] directories = Directory.GetDirectories(path);
                foreach (string directory in directories)
                {
                    DirectoryInfo di = new DirectoryInfo(directory);
                    CurrentFoldersFiles.Add(di);
                }
            }
            catch (Exception e)
            {
                ConsoleDrawings.PrintError(e.Message);
                CurrentFoldersFiles.Clear();
                return;
            }

            try
            {
                string[] files = Directory.GetFiles(path);
                foreach (string file in files)
                {
                    FileInfo fi = new FileInfo(file);
                    CurrentFoldersFiles.Add(fi);
                }
            }
            catch (Exception e)
            {
                ConsoleDrawings.PrintError(e.Message);
                CurrentFoldersFiles.Clear();
                return;
            }
        }
예제 #7
0
 static void ReadFile(string path)
 {
     try
     {
         if (!File.Exists(path))
         {
             ConsoleDrawings.PrintError($"Файл {path} не существует/не доступен");
         }
         else
         {
             ConsoleDrawings.PrintFileContent(path);
         }
     }
     catch (Exception e)
     {
         ConsoleDrawings.PrintError($"Ошибка чтения файла: {e.Message}");
     }
 }
예제 #8
0
        static void Delete(string path)
        {
            FileInfo      file;
            DirectoryInfo directories;

            try
            {
                FileAttributes attr = File.GetAttributes(path);
                if (attr.HasFlag(FileAttributes.Directory))
                {
                    directories = new DirectoryInfo(path);
                    foreach (DirectoryInfo dir in directories.GetDirectories())
                    {
                        ConsoleDrawings.PrintInformation($"Удаляем {dir.Name}");
                        dir.Delete(true);
                    }
                    if (directories.FullName == CurrentPath)
                    {
                        CurrentPath = directories.Parent.FullName;//присваиваем, чтобы сработала процедура, которая обновит список
                        ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, 1);
                    }
                    directories.Delete(true);
                }
                else
                {
                    file = new FileInfo(path);
                    file.Delete();
                    if (file.Directory.FullName == CurrentPath)
                    {
                        CurrentPath = file.Directory.FullName;//присваиваем, чтобы сработала процедура, которая обновит список
                        ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, 1);
                    }
                }
                ConsoleDrawings.PrintInformation("Удаление завершено");
            }
            catch (Exception e)
            {
                ConsoleDrawings.PrintError(e.Message);
                return;
            }
        }
예제 #9
0
        static void Main(string[] args)
        {
            //фиксируем размеры окна, чтобы нельзя было его изменить
            WindowUtility.FixeConsoleWindow(Configuration.ConsoleHeight, Configuration.ConsoleWidth);

            //рисуем рамку для основной панели с папками/файлами
            ConsoleDrawings.PrintFrameLines(0, 0, Console.WindowWidth, Configuration.MainPanelHeight);
            ConsoleDrawings.PrintFrameLines(0, Configuration.MainPanelHeight, Console.WindowWidth, Configuration.InfoPanelHeight);


            //считывание сохраненного пути с последнего сеанса работы
            if (File.Exists("last.state"))
            {
                using (StreamReader sr = new StreamReader("last.state")) //File.OpenText(inputFile))
                {
                    string strState = "";
                    try
                    {
                        strState = sr.ReadLine();
                    }
                    catch (Exception)
                    {
                        CurrentPath = "C:\\";
                    }
                    CurrentPath = strState;
                }
            }
            else
            {
                CurrentPath = "C:\\";
            }
            ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, 1);
            //справка:
            ConsoleDrawings.PrintInformation("help - список всех поддерживаемых комманд");

            bool          exit      = false;
            List <string> arguments = new List <string>();


            while (!exit)
            {
                ConsoleDrawings.TakeNewCommand();
                currentCommand = Console.ReadLine();
                ConsoleDrawings.ClearMessageLine();
                arguments.Clear();//по завершении обработки команды очищаем список аргументов, чтобы корректно обработать следующую команду
                arguments.AddRange(currentCommand.Split(' '));

                string theCommand = arguments[0];
                arguments.Remove(theCommand);
                switch (theCommand.ToLower().Trim())
                {
                case "exit":
                    SaveLastState();
                    exit = true;
                    break;

                case "ls":
                    LSCommand(arguments);
                    break;

                case "cp":
                    CPCommand(arguments);
                    break;

                case "rm":
                    RMCommand(arguments);
                    break;

                case "file":
                    FILECommand(arguments);
                    break;

                case "help":
                    ConsoleDrawings.PrintInformation("Поддерживаемые команды: exit; ls; cp; rm; file. Введите команду с ключом /? чтобы получить подробное описание");
                    break;

                case "":
                    arguments.Clear();
                    break;

                default:
                    ConsoleDrawings.PrintWarning($"Невозможно обработать команду {theCommand}");
                    arguments.Clear();
                    break;
                }
            }
        }
예제 #10
0
 static void CPCommand(List <string> arguments)
 {
     if (arguments.Count == 0)
     {
         ConsoleDrawings.PrintError("Неверные параметры...");
         return;
     }
     else if (arguments.Count == 1)
     {
         if (arguments[0].Trim() == "/?")
         {
             ConsoleDrawings.PrintInformation("cp <путь - откуда копируем> <путь куда копируем> - копирование файла/каталога");
         }
         else
         {
             ConsoleDrawings.PrintError("Неправильный вызов команды cp");
         }
     }
     else if (arguments.Count == 2)
     {
         string source = arguments[0];
         string dest   = arguments[1];
         if (source.Trim() == dest.Trim())
         {
             ConsoleDrawings.PrintError("Нельзя скопировать файл/папку саму в себя");
         }
         else if (source.Trim() == "" || dest.Trim() == "")
         {
             ConsoleDrawings.PrintError("Неверные аргументы");
         }
         else
         {
             Copy(source, dest);
         }
     }
     else
     {
         string resSourcePath    = arguments[0];
         string resDestPath      = "";
         int    indexOfStartDest = 0;//индекс начала второго параметра
         for (int i = 1; i < arguments.Count; i++)
         {
             resSourcePath += " ";
             if (arguments[i].Length > 1)
             {
                 if (arguments[i].Substring(1, 1) != ":")
                 {
                     resSourcePath += arguments[i];
                 }
                 else
                 {
                     indexOfStartDest = i;
                     break;
                 }
             }
             else
             {
                 resSourcePath += arguments[i];
             }
         }
         resSourcePath = resSourcePath.Trim();
         for (int i = indexOfStartDest; i < arguments.Count; i++)
         {
             resDestPath += arguments[i];
             resDestPath += " ";
         }
         resDestPath = resDestPath.Trim();
         Copy(resSourcePath, resDestPath);
     }
 }
예제 #11
0
        static void LSCommand(List <string> arguments)
        {
            int pageNum;

            if (arguments.Count == 0)
            {
                ConsoleDrawings.PrintError("Неверные параметры...");
                return;
            }
            else if (arguments.Count == 1)
            {
                if (arguments[0] == "/?")
                {
                    ConsoleDrawings.PrintInformation("ls <путь> <номер страницы> - команда выводит дерево указанного каталога с указанным номером страницы");
                }
                else if (arguments[0] == "..")
                {
                    DirectoryInfo parentDirectory = Directory.GetParent(CurrentPath);
                    if (parentDirectory == null)
                    {
                        ConsoleDrawings.PrintWarning("Не существует родительской директории для указанного каталога");
                    }
                    else
                    {
                        CurrentPath = parentDirectory.FullName;
                        ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, 1);
                    }
                }
                else //if(Directory.Exists(arguments[0]))//если не указан номер страницы, выводим первую
                {
                    CurrentPath = arguments[0];
                    ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, 1);
                }
            }
            else if (arguments.Count == 2)  //если два аргумента в команде, значит можно реализовать команду
            {
                CurrentPath = arguments[0]; //первый аргумент должен быть путь
                try
                {
                    pageNum = Convert.ToInt32(arguments[1]);
                }
                catch (FormatException)
                {
                    pageNum = 1;
                    ConsoleDrawings.PrintWarning("Некорректный аргумент <номер страницы> - выводим 1ю страницу...");
                }
                if (pageNum == 0)
                {
                    pageNum = 1;
                }
                ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, pageNum);
            }
            else//если аргументов более 2х, возможно путь разделен пробелами
            {
                //пытаемся собрать путь, предположив, что он разделен пробелами
                string resPath = "";
                for (int i = 0; i < arguments.Count - 1; i++)
                {
                    resPath += arguments[i];
                    resPath += " ";
                }
                resPath = resPath.Trim();
                try
                {
                    pageNum = Convert.ToInt32(arguments[arguments.Count - 1]);
                }
                catch (FormatException)
                {
                    resPath += " ";
                    resPath += arguments[arguments.Count - 1];
                    pageNum  = 1;
                }
                CurrentPath = resPath;
                ConsoleDrawings.PrintFoldersTree(CurrentPath, CurrentFoldersFiles, pageNum);
                //ConsoleDrawings.PrintError("Невозможно распознать команду, - аргументов более 2х");
            }
        }
        public static void PrintInformation(string rootFolder, List <FileSystemInfo> content)
        {
            ClearInformationPanel();
            int positionX, positionY;

            positionX = 2;
            positionY = Configuration.MainPanelHeight + 1;
            Console.SetCursorPosition(positionX, positionY);
            positionY++;
            Console.ForegroundColor = infoColor;
            Console.BackgroundColor = textBackgroundColor;
            Console.WriteLine($"                   Путь: {rootFolder}");
            DirectoryInfo di = new DirectoryInfo(rootFolder);

            Console.SetCursorPosition(positionX, positionY);
            positionY++;
            Console.WriteLine($"          Дата создания: {di.CreationTime.ToString("dd.MM.yyyy")}");
            Console.SetCursorPosition(positionX, positionY);
            positionY++;
            Console.WriteLine($"    Последнее изменение: {di.LastWriteTime.ToString("dd.MM.yyyy")}");

            string attributes;

            if (rootFolder.Length > 4)
            {
                attributes = "               Атрибуты: ";
                if (di.Attributes.HasFlag(FileAttributes.ReadOnly))
                {
                    attributes += "Только для чтения | ";
                }
                if (di.Attributes.HasFlag(FileAttributes.Archive))
                {
                    attributes += "Архивный | ";
                }
                if (di.Attributes.HasFlag(FileAttributes.System))
                {
                    attributes += "Системный | ";
                }
                if (di.Attributes.HasFlag(FileAttributes.Hidden))
                {
                    attributes += "Скрытый | ";
                }
                if (attributes != "               Атрибуты: ")
                {
                    attributes = attributes.Substring(0, attributes.Length - 3);
                    Console.SetCursorPosition(positionX, positionY);
                    positionY++;
                    Console.WriteLine(attributes);
                }
            }
            else
            {
                try
                {
                    DriveInfo drive = new DriveInfo(rootFolder);
                    Console.SetCursorPosition(positionX, positionY);
                    positionY++;
                    Console.WriteLine($"Доступно места на диске: {ToPrettySize(drive.AvailableFreeSpace)}");
                    Console.SetCursorPosition(positionX, positionY);
                    positionY++;
                    Console.WriteLine($"            Метка диска: {drive.VolumeLabel}");
                }
                catch (Exception) { }
            }



            //Подсчитываем размер текущей директории в потоке, чтобы можно было остановить его, в случае смены директории
            long fullDirSize = 0;

            if (CalculateFolderSize != null)
            {
                cancelTokenSource.Cancel();
            }
            Action <object> action = (object obj) =>
            {
                GetTotalSize(rootFolder, ref fullDirSize, token);
                string size;
                try
                {
                    size = ToPrettySize(fullDirSize);
                }
                catch (Exception)
                {
                    size = "0";
                }
                if (fullDirSize != -1)
                {
                    Console.SetCursorPosition(positionX, positionY);
                    Console.Write(new string(' ', Configuration.ConsoleWidth - 3));
                    Console.SetCursorPosition(positionX, positionY);
                    positionY++;
                    Console.ForegroundColor = infoColor;
                    Console.BackgroundColor = textBackgroundColor;
                    Console.WriteLine($"            Общий объем: {size}");
                }
                ConsoleDrawings.TakeNewCommand();
            };

            try
            {
                cancelTokenSource = new CancellationTokenSource();
                token             = cancelTokenSource.Token;
                Console.SetCursorPosition(positionX, positionY);
                Console.ForegroundColor = infoColor;
                Console.BackgroundColor = textBackgroundColor;
                Console.WriteLine($"            Общий объем: <расчитывается...>");
                CalculateFolderSize = Task.Factory.StartNew(action, token);
                ConsoleDrawings.TakeNewCommand();
            }
            catch (Exception e)
            {
                //PrintError(e.Message);
            }
        }
        public static void PrintFoldersTree(string rootFolder, List <FileSystemInfo> content, int pageNum)//вовод дерева каталогов
        {
            if (content.Count == 0)
            {
                //если список файлов/папок пуст, ничего не выводим, просто оставляем старое дерево
                if (!Directory.Exists(rootFolder))
                {
                    return;
                }
                //если директория существует, но она пуста, то дерево все равно надо вывести
            }
            //рисуем в заголовке текущую директорию + номер страницы
            int    maxPage;
            string header = rootFolder;

            if (content.Count != 0)
            {
                float pageNumCoefficent = (float)content.Count / (float)Configuration.ElementsOnPage;
                maxPage = (int)Math.Ceiling(pageNumCoefficent);
            }
            else // если папки отсутствуют в текущей директории вручную пишем количество страниц
            {
                maxPage = 1;
            }
            if (pageNum > maxPage)
            {
                pageNum = maxPage;
                ConsoleDrawings.PrintWarning($"Некорректный аргумент <номер страницы> максимально допустимая страница - {maxPage}");
            }
            header += $" - [{pageNum}/{maxPage}]";
            PrintMainPanelHeader(header);



            int positionX, positionY;

            positionX = 2;
            positionY = 1;
            ClearMainPanel();

            Console.SetCursorPosition(positionX, positionY);
            Console.WriteLine(rootFolder);
            positionY++;
            if (pageNum != 1)//если выводим не 1ю страницу, то рисуем дополнительно "<..>", чтобы было понятно, то это не начало дерева
            {
                Console.SetCursorPosition(positionX, positionY);
                Console.Write(TreeLines.DownContinue);
                Console.Write(TreeLines.Right);
                Console.Write("<..>");
                positionY++;
            }

            for (int i = (pageNum - 1) * Configuration.ElementsOnPage; i < content.Count; i++)
            {
                Console.SetCursorPosition(positionX, positionY);
                positionY++;
                if (i + 1 == content.Count)//если последний элемент дерева, то рисуем завершающую закорючку
                {
                    Console.Write(TreeLines.DownLast);
                }
                else//иначе продолжающаяся закорючка. В этом случае будет понятно, что существует дополнительная страница
                {
                    Console.Write(TreeLines.DownContinue);
                }
                Console.Write(TreeLines.DoubleRight);

                if (content[i] is DirectoryInfo)
                {
                    Console.ForegroundColor = textColor;
                }
                else
                {
                    Console.ForegroundColor = fileColor;
                }
                Console.Write("{0, -70}", content[i].Name);
                Console.ForegroundColor = textColor;

                if (content[i] is DirectoryInfo)
                {
                    /*try
                     * {
                     *  string[] directories = Directory.GetDirectories(content[i].FullName);
                     *  //если в конкретной папке есть подпапки, помечаем её '[+]', чтобы указать, что есть смысл её просматривать:
                     *  if (directories.Length != 0)
                     *  {
                     *      Console.ForegroundColor = warningColor;
                     *      Console.WriteLine("[+]");
                     *  }
                     * }
                     * catch (Exception)
                     * {
                     *  Console.Write("\n");
                     *  continue;
                     * }*/
                    Console.ForegroundColor = textColor;
                    Console.Write("{0, -15}", "<ПАПКА>");
                }
                else if (content[i] is FileInfo)
                {
                    Console.ForegroundColor = textColor;
                    string memSize;
                    try
                    {
                        memSize = ToPrettySize(((FileInfo)content[i]).Length);
                    }
                    catch (Exception)
                    {
                        memSize = "0";
                    }
                    //для более читабельного вывода, дополняем строку проблеми
                    string sep = new string(' ', 7 - memSize.Length);
                    memSize = sep + memSize;
                    Console.Write("{0, -15}", memSize);
                }
                Console.Write("{0, -5}", content[i].LastAccessTime.ToString("dd.MM.yyyy"));
                Console.Write("\t");
                //вывод атрибутов
                if ((content[i].Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                {
                    Console.Write("r");
                }
                else
                {
                    Console.Write(".");
                }
                if ((content[i].Attributes & FileAttributes.Archive) == FileAttributes.Archive)
                {
                    Console.Write("a");
                }
                else
                {
                    Console.Write(".");
                }
                if ((content[i].Attributes & FileAttributes.System) == FileAttributes.System)
                {
                    Console.Write("s");
                }
                else
                {
                    Console.Write(".");
                }
                if ((content[i].Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    Console.Write("h");
                }
                else
                {
                    Console.Write(".");
                }

                //    Console.Write("{0, 0}", content[i].Attributes.ToString());
                Console.Write("\n");
                if (positionY > Configuration.ElementsOnPage)
                {
                    break;
                }
            }
            if (rootFolder != CurrentFolder)//делаем эту проверку, чтобы не перерасчитывать общий объем папки
            {
                PrintInformation(rootFolder, content);
            }
            CurrentFolder = rootFolder;
        }