static void Main(string[] args) { DirectoryInfo Dir = new DirectoryInfo(@"C:\Users\Admin\Desktop\Alikhan"); Lawer l = new Lawer // папкаларды,файлдарды,индексті көрсететін класс құрамыз { DirCon = Dir.GetDirectories(), //DirCon массиві үшін Dir директорясында папканың адресін көрсетеміз FileCon = Dir.GetFiles(), selectedIndex = 0 }; l.Draw(); FSIMode Mod = FSIMode.DirectoryInfo; //папкалар үшін жаңа FSI(enum) құрамыз Stack <Lawer> contral = new Stack <Lawer>(); //жаңа стэк құрамыз contral.Push(l); // стэкке class(l) ді енгіземіз bool work = false; while (!work) { if (Mod == FSIMode.DirectoryInfo) //егер FSI(enum) папка болса { contral.Peek().Draw(); //стэкка Draw функциясын көрсетеміз } ConsoleKeyInfo key = Console.ReadKey(); // басылған консолдың клавиштерін сипаттайды switch (key.Key) // { case ConsoleKey.Escape: //егер Escape-ты бассақ work = true; //онда консол жұмысын тоқтатады break; } } }
static bool pathExists(string path, FSIMode mode) // Проверка пути { if ((mode == FSIMode.DirectoryInfo && new DirectoryInfo(path).Exists) || (mode == FSIMode.FileInfo && new FileInfo(path).Exists)) { return(true); } else { return(false); } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\A5LAN\Desktop\pp2"); Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; break; case ConsoleKey.Escape: esc = true; break; } } }
static void Main(string[] args) { FSIMode mode = FSIMode.Zip; int mode2 = 2; //0 - dir //1 - file //2 - zip //.. if (mode2 == 0) { Console.WriteLine("DIR!"); } else if (mode2 == 1) { Console.WriteLine("FILE!"); } else if (mode2 == 2) { Console.WriteLine("ZIP!"); } //.. //... //.. if (mode == FSIMode.Dir) { Console.WriteLine("DIR!"); } else if (mode == FSIMode.File) { Console.WriteLine("FILE!"); } else if (mode == FSIMode.Zip) { Console.WriteLine("ZIP!"); } }
static void Main(string[] args) { DirectoryInfo dirI = new DirectoryInfo(@"C:\Users\User\easy.cpp"); if (!dirI.Exists) { Console.WriteLine("Directory does not exist"); return; } Layer l = new Layer { DirContent = dirI.GetDirectories(), FileContent = dirI.GetFiles(), curIndex = 0 }; Stack <Layer> st = new Stack <Layer>(); st.Push(l); bool esc = false; FSIMode curMode = FSIMode.Directory; while (!esc) { if (curMode == FSIMode.Directory) { st.Peek().Draw(); Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Delete: Del | Rename: F4 | Back: Backspace | Exit: Esc"); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) { case ConsoleKey.UpArrow: if (st.Peek().curIndex > 0) { st.Peek().curIndex--; } else { st.Peek().curIndex = st.Peek().DirContent.Length + st.Peek().FileContent.Length - 1; } break; case ConsoleKey.DownArrow: if (st.Peek().DirContent.Length + st.Peek().FileContent.Length - 1 > st.Peek().curIndex) { st.Peek().curIndex++; } else { st.Peek().curIndex = 0; } break; case ConsoleKey.Enter: if (st.Peek().DirContent.Length + st.Peek().FileContent.Length == 0) { break; } int index = st.Peek().curIndex; if (index < st.Peek().DirContent.Length) { DirectoryInfo d = st.Peek().DirContent[index]; st.Push(new Layer { DirContent = d.GetDirectories(), FileContent = d.GetFiles(), curIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(st.Peek().FileContent[index - st.Peek().DirContent.Length].FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: if (curMode == FSIMode.Directory) { if (st.Count > 1) { st.Pop(); } } else { curMode = FSIMode.Directory; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: esc = true; break; case ConsoleKey.Delete: if (curMode != FSIMode.Directory || (st.Peek().DirContent.Length + st.Peek().FileContent.Length) == 0) { break; } index = st.Peek().curIndex; int ind = index; if (index < st.Peek().DirContent.Length) { st.Peek().DirContent[index].Delete(true); } else { st.Peek().FileContent[index - st.Peek().DirContent.Length].Delete(); } int numofcontent = st.Peek().DirContent.Length + st.Peek().FileContent.Length - 2; st.Pop(); if (st.Count == 0) { Layer nl = new Layer { DirContent = dirI.GetDirectories(), FileContent = dirI.GetFiles(), curIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; st.Push(nl); } else { index = st.Peek().curIndex; DirectoryInfo di = st.Peek().DirContent[index]; Layer nl = new Layer { DirContent = di.GetDirectories(), FileContent = di.GetFiles(), curIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; st.Push(nl); } break; case ConsoleKey.F4: if (st.Peek().DirContent.Length + st.Peek().FileContent.Length == 0) { break; } index = st.Peek().curIndex; string name, fullname; int selectedMode; if (index < st.Peek().DirContent.Length) { name = st.Peek().DirContent[index].Name; fullname = st.Peek().DirContent[index].FullName; selectedMode = 1; } else { name = st.Peek().FileContent[index - st.Peek().DirContent.Length].Name; fullname = st.Peek().FileContent[index - st.Peek().DirContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); Console.WriteLine("Please enter the new name, to rename {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); while (newname.Length == 0 || exist(fullname + newname, selectedMode)) { Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); } Console.WriteLine(selectedMode); if (selectedMode == 1) { new DirectoryInfo(st.Peek().DirContent[index].FullName).MoveTo(fullname + newname); } else { new FileInfo(st.Peek().FileContent[index - st.Peek().DirContent.Length].FullName).MoveTo(fullname + newname); } index = st.Peek().curIndex; ind = index; numofcontent = st.Peek().DirContent.Length + st.Peek().FileContent.Length - 1; st.Pop(); if (st.Count == 0) { Layer nl = new Layer { DirContent = dirI.GetDirectories(), FileContent = dirI.GetFiles(), curIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; st.Push(nl); } else { index = st.Peek().curIndex; DirectoryInfo di = st.Peek().DirContent[index]; Layer nl = new Layer { DirContent = di.GetDirectories(), FileContent = di.GetFiles(), curIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; st.Push(nl); } break; default: break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(Console.ReadLine()); FarManager l = new FarManager { Content = dir.GetFileSystemInfos(), SelectedIndex = 0, }; Stack <FarManager> history = new Stack <FarManager>(); history.Push(l); bool esc = false; FSIMode curMode = FSIMode.DirectoryInfo; while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Show(); } ConsoleKeyInfo KeyInfo = Console.ReadKey(); switch (KeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: int index = history.Peek().SelectedIndex; FileSystemInfo fs = history.Peek().Content[index]; if (fs.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; DirectoryInfo dr = fs as DirectoryInfo; history.Push(new FarManager { Content = dr.GetFileSystemInfos(), SelectedIndex = 0 }); } else { curMode = FSIMode.FileInfo; FileStream fsm = new FileStream(fs.FullName, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fsm); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } break; case ConsoleKey.Backspace: if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ResetColor(); } break; case ConsoleKey.Delete: history.Peek().Delete(); break; case ConsoleKey.Tab: history.Peek().ReName(); break; case ConsoleKey.Escape: esc = true; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\A5LAN\Desktop\pp2"); Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; // DirectoryInfo d = (DirectoryInfo)fsi; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: esc = true; break; case ConsoleKey.Delete: int x2 = history.Peek().SelectedIndex; FileSystemInfo fileSystemInfo2 = history.Peek().Content[x2]; if (fileSystemInfo2.GetType() == typeof(DirectoryInfo)) { DirectoryInfo d = fileSystemInfo2 as DirectoryInfo; Directory.Delete(fileSystemInfo2.FullName, true); history.Peek().Content = d.Parent.GetFileSystemInfos(); } else { FileInfo f = fileSystemInfo2 as FileInfo; File.Delete(fileSystemInfo2.FullName); history.Peek().Content = f.Directory.GetFileSystemInfos(); } history.Peek().SelectedIndex--; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\A5LAN\Desktop\ppp"); // path where file is located Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; // DirectoryInfo d = (DirectoryInfo)fsi; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: // if press the ecs the program finishes esc = true; break; case ConsoleKey.Delete: // if press the delete key the folder or file would be deleted int x2 = history.Peek().SelectedIndex; FileSystemInfo fileSystemInfo2 = history.Peek().Content[x2]; if (fileSystemInfo2.GetType() == typeof(DirectoryInfo)) { DirectoryInfo d = fileSystemInfo2 as DirectoryInfo; Directory.Delete(fileSystemInfo2.FullName, true); history.Peek().Content = d.Parent.GetFileSystemInfos(); } else { FileInfo f = fileSystemInfo2 as FileInfo; File.Delete(fileSystemInfo2.FullName); history.Peek().Content = f.Directory.GetFileSystemInfos(); } history.Peek().SelectedIndex--; break; case ConsoleKey.F: int x3 = history.Peek().SelectedIndex; FileSystemInfo fileSystemInfo3 = history.Peek().Content[x3]; Console.WriteLine("Enter new name:"); string name = Console.ReadLine(); string prev = fileSystemInfo3.FullName; string newName = Path.Combine(Path.GetDirectoryName(prev), name); Directory.Move(prev, newName); history.Peek().Draw(); break; } } }
static void Main(string[] args) //основная часть программы { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\vsavg\Desktop"); //creating new directory if (!dir.Exists) //if directory doesnt exists we write it { Console.WriteLine("Directory not exist"); //на случай, если данной директории не существует return; } Layer l = new Layer //creaating new layers for better showing of far manger work content is important { DirectoryContent = dir.GetDirectories(), //get directories function FileContent = dir.GetFiles(), //get files function SelectedIndex = 0 //index we start }; Stack <Layer> history = new Stack <Layer>(); //создаем именно Stack для работы по принципу LIFO Stack<Layer> history = new Stack<Layer>() history.Push(l); //adding to history new level through push bool esc = false; //пока кнопка выхода не нажата работает следующее: FSIMode curMode = FSIMode.DirectoryInfo; //idk what's that people write like that FSIMode curMode = FSIMode.DirectoryInfo; while (!esc) //until escape is not choosen { if (curMode == FSIMode.DirectoryInfo) //current mode equals to fsi mode in directory info { history.Peek().Draw(); //reaading through peek its function and draw what we have its also a function Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Delete: Del | Rename: F4 | Back: Backspace | Exit: Esc"); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) //различные случаи или кейсы при которых работают кнопки { case ConsoleKey.UpArrow: if (history.Peek().SelectedIndex > 0) //при перемещении кнопок вниз вверх stack начинает читать головной элемент как выбранный нами индекс more than 0 we peek it -- { history.Peek().SelectedIndex--; } break; case ConsoleKey.DownArrow: //for down arrow we peek dircont length+ filecont length -1 more than selected index if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1 > history.Peek().SelectedIndex) { history.Peek().SelectedIndex++; //adding to peek ++ selected index } break; case ConsoleKey.Enter: if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) //складывает в stack все элементы из файлов и папок dircont filecont leng { break; } int index = history.Peek().SelectedIndex; //index equals to selected if (index < history.Peek().DirectoryContent.Length) //если меньше количества папок то читаем как папку типа до крайней папки идут другие папки history.Peek().DirectoryContent.Length { DirectoryInfo d = history.Peek().DirectoryContent[index]; history.Push(new Layer //новый слой для появления новых папой и файлов in dir info d history.Peek().DirectoryContent[index] { DirectoryContent = d.GetDirectories(), //getting directories content FileContent = d.GetFiles(), //getting files content SelectedIndex = 0 }); } else { curMode = FSIMode.File; //we have fsimode file we gonna open it using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) //если это файл то делаем проверку на место в ряду папок и файлов, затем открываем и читаем (history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read { using (StreamReader sr = new StreamReader(fs)) //читает файлы that in using fs { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); //read file polnost'u } } } break; case ConsoleKey.Backspace: //going back if (curMode == FSIMode.DirectoryInfo) //current fsi mode for dir info { if (history.Count > 1) //убираем с истории слои чтобы вернуться в предыдущий то есть выйти это для папок в папках и тд history.Count > 1 pop deletes { history.Pop(); } } else { curMode = FSIMode.DirectoryInfo; //если это первый слой то просто выходим из программы Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: //going out prosto bool esc equals true esc = true; break; case ConsoleKey.Delete: //deleting files if (curMode != FSIMode.DirectoryInfo || (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) //cur mode should be equal to FSIMode.DirectoryInfo // history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0 then deleting breaks { break; } index = history.Peek().SelectedIndex; //присваем индексу значение выбранного history.Peek().SelectedIndex int ind = index; //now ind equals to index if (index < history.Peek().DirectoryContent.Length) //сравниваем с индексом расположения папки index < history.Peek().DirectoryContent.Length { history.Peek().DirectoryContent[index].Delete(true); //если это папка то удаляем ее history.Peek().DirectoryContent[index].Delete(true) } else { history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete(); //случай для файлов history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete() } int numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2; // numofcontent -2 because we have 2 writelines that cannot be divided history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2 history.Pop(); //deleting files if (history.Count == 0) //first layes 0 { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), //get papkis FileContent = dir.GetFiles(), //get files SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) //idk what is that sorry( Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; //if history more than 0 index = history.Peek().SelectedIndex DirectoryInfo di = history.Peek().DirectoryContent[index]; //di direcory equals to hist peek dircont arrays index history.Peek().DirectoryContent[index] Layer nl = new Layer { DirectoryContent = di.GetDirectories(), //get dirs content FileContent = di.GetFiles(), //get files content SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) //idk what is that sorry( Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; case ConsoleKey.F4: //renaming! if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) //both contents length shouldnt be equal to zero so it breaks { break; } index = history.Peek().SelectedIndex; //index equals hist peek selected index string name, fullname; int selectedMode; if (index < history.Peek().DirectoryContent.Length) //случай для папок (index < history.Peek().DirectoryContent.Length) { name = history.Peek().DirectoryContent[index].Name; //name equals to name we already have history.Peek().DirectoryContent[index].Name; fullname = history.Peek().DirectoryContent[index].FullName; //same with fullname selectedMode = 1; //choosing mode 1 } else { name = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name; //для файлов history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name fullname = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName; //same as name selectedMode = 2; //cause files mode is 2 } fullname = fullname.Remove(fullname.Length - name.Length); //remove fullname.Length - name.Length deletes all names Console.WriteLine("Please enter the new name, to rename {0}:", name); // creating new name Console.WriteLine(fullname); //and fullname string newname = Console.ReadLine(); //reading through console newname while (newname.Length == 0 || pathExists(fullname + newname, selectedMode)) //even no new name of pathExists(fullname + newname, selectedMode) { Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); //another try to newname = Console.ReadLine() } Console.WriteLine(selectedMode); // we have 2 modes for dirs and files if (selectedMode == 1) //if dirs new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); { new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); //moving to full+name } else //mode 2 for files FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); { new FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); } index = history.Peek().SelectedIndex; //new index equals to selected ind = index; //ind equals to index numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; //history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1 history.Pop(); //deleting if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; default: break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo("/Users/meruyerttastandiyeva/Desktop"); //make a reference to a directory Layer l = new Layer //call constructor with parameters { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); //create a stack using the constructor history.Push(l); //insert an element at the top of the stack bool esc = false; //create a boolean variable FSIMode curMode = FSIMode.DirectoryInfo; while (!esc)//use while loop for executing a statements while a specified boolean expression is true { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey();//create a variable that identifies the console key that was pressed switch (consolekeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; //incrementing index break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; //decrementing index break; case ConsoleKey.Enter: int index = history.Peek().SelectedIndex; if (index < history.Peek().DirectoryContent.Length) { DirectoryInfo d = history.Peek().DirectoryContent[index]; history.Push(new Layer //insert an element at the top of the stack { DirectoryContent = d.GetDirectories(), FileContent = d.GetFiles(), SelectedIndex = 0 }); } else //if it is a textfile we enter to it { curMode = FSIMode.File; using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) //open a textfile to read from it { using (StreamReader sr = new StreamReader(fs)) //create a stream reader and link it to the file stream { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); //read all the data from textfile and display it } //"using" statement closes the stream } } break; case ConsoleKey.Backspace: if (curMode == FSIMode.DirectoryInfo) { if (history.Count > 1) { history.Pop(); //removes and returns the object at the top of the stack } } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: esc = true; break; case ConsoleKey.Delete: index = history.Peek().SelectedIndex; int ind = index; if (index < history.Peek().DirectoryContent.Length) { history.Peek().DirectoryContent[index].Delete(true); //delete a directory } else { history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete(); //delete a file } int numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2; history.Pop(); //removes and returns the object at the top of the stack if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); //insert an element at the top of the stack } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); //insert an element at the top of the stack } break; case ConsoleKey.A: index = history.Peek().SelectedIndex; string name, fullname; int selectedMode; if (index < history.Peek().DirectoryContent.Length) { name = history.Peek().DirectoryContent[index].Name; fullname = history.Peek().DirectoryContent[index].FullName; selectedMode = 1; } else { name = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name; fullname = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); Console.WriteLine("Please enter the new name, to rename {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); while (newname.Length == 0) { Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); } Console.WriteLine(selectedMode); if (selectedMode == 1) { new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); //renames a directory } else { new FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); //renames a file } index = history.Peek().SelectedIndex; ind = index; numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; history.Pop(); //removes and returns the object at the top of the stack if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; default: break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Asus\source\repos"); if (!dir.Exists) //если папке не существует { Console.WriteLine("Directory not exist"); //вывожу на консоль что ее нет return; } Layer l = new Layer // { DirectoryContent = dir.GetDirectories(), //directorycontent содержит в себе папки внутри папки FileContent = dir.GetFiles(), //filecomtent содержит в себе файлы папки SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; FSIMode curMode = FSIMode.DirectoryInfo; //вызываю нумерованный список while (!esc) //пока не сделан выход { if (curMode == FSIMode.DirectoryInfo) //текущее состояние это папка { history.Peek().Draw(); //вызываю функцию draw Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Delete: Del | Rename: F4 | Back: Backspace | Exit: Esc"); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) { case ConsoleKey.UpArrow: //если нажата клавиша стрелки вверх if (history.Peek().SelectedIndex > 0) //если выбранный объект индекс больше нуля { history.Peek().SelectedIndex--; //то идет вниз } break; case ConsoleKey.DownArrow: if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1 > history.Peek().SelectedIndex) { history.Peek().SelectedIndex++; //идем вверх } break; case ConsoleKey.Enter: if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) //если ничего нет то выходим из программы { break; } int index = history.Peek().SelectedIndex; //создаем переменную которой присваиваем значение выбранного объекта if (index < history.Peek().DirectoryContent.Length) //если индекс меньше кол-ва папок { DirectoryInfo d = history.Peek().DirectoryContent[index]; history.Push(new Layer { DirectoryContent = d.GetDirectories(), //выводим его папки FileContent = d.GetFiles(), //выводим файлы SelectedIndex = 0 }); } else { curMode = FSIMode.File; //если же состояние файлов то мы его открываем и выводим все что находится в файлах using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; //выходим case ConsoleKey.Backspace: //если нажата клавиша "назад" if (curMode == FSIMode.DirectoryInfo) //если текущее состояние папка { if (history.Count > 1) //если кол-во элементов больше 1 { history.Pop(); //то мы извлекаем и возвращаем первый элемент стека } } else { curMode = FSIMode.DirectoryInfo; //если текущее состояние это папка Console.ForegroundColor = ConsoleColor.White; //выводим цвет букв белый } break; //выходим case ConsoleKey.Escape: //если нажата клавиша выхода esc = true; //если нажата то выходим break; case ConsoleKey.Delete: //если нажата клавиша удаления if (curMode != FSIMode.DirectoryInfo || (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) //если текущее состояние не папка или там ничего нет то выходим { break; } index = history.Peek().SelectedIndex; //создаю переменную int ind = index; if (index < history.Peek().DirectoryContent.Length) //если же папка то удаляем ее { history.Peek().DirectoryContent[index].Delete(true); } else { history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete(); //если файл то удаляем его } int numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2; //порядок поменялся после удаления history.Pop(); //извлекаем и возвращаем первый элемент стека if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; case ConsoleKey.F4: //если нажата клавиша переименования папки if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) //если ничего нет то выходим { break; } index = history.Peek().SelectedIndex; string name, fullname; int selectedMode; if (index < history.Peek().DirectoryContent.Length) //если это папка { name = history.Peek().DirectoryContent[index].Name; //то берем название папки fullname = history.Peek().DirectoryContent[index].FullName; //берем путь selectedMode = 1; } else { name = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name; //если файл то также берем название файла и путь к нему fullname = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); //меняем путь то есть убираем в конце пути название Console.WriteLine("Please enter the new name, to rename {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); while (newname.Length == 0 || pathExists(fullname + newname, selectedMode)) //если не введено или такой путь существует { Console.WriteLine("This directory was created, Enter the new one"); //то выводим на экран что такое название уже есть newname = Console.ReadLine(); //вводим новый } Console.WriteLine(selectedMode); //выводим if (selectedMode == 1) //если это папка то выводим его новое название { new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); } else { new FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); } index = history.Peek().SelectedIndex; ind = index; numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; history.Pop(); if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; default: break; } } }
static void Main(string[] args) { DirectoryInfo startPath = new DirectoryInfo(@"C:\Users\aruzh"); // Объявляем начальные значения if (!startPath.Exists) { // Проверяем путь Console.WriteLine("Directory not exist"); return; } Layer startLayer = new Layer { // Создаем класс Layer -> (контенты, выделенный контент, отрезок для вывода и начальный индекс файла) Content = Combine(startPath.GetDirectories(), startPath.GetFiles()), SelectedIndex = 0, Left = 0, Right = 20, // Максимально можно показывать 25 строк FileIndex = startPath.GetDirectories().Length // начальный индекс файлов }; Stack <Layer> history = new Stack <Layer>(); // Стек для хранения Layer-ов history.Push(startLayer); bool esc = false; FSIMode LayerMode = FSIMode.DirectoryInfo; // LayerMode - текущее состояние Layer-а FSIMode SelectedMode = FSIMode.DirectoryInfo; // SelectedMode - состояние выделенного контента для удобства while (!esc) { Layer l = history.Peek(); // для удобства возьмем текущий Слой(Layer) if (LayerMode == FSIMode.DirectoryInfo) { // Чтобы обновлять Слой, текущее состояние должно быть папкой if (l.Content.Length > 0) { SelectedMode = (l.Content[l.SelectedIndex].GetType() == typeof(DirectoryInfo)) ? FSIMode.DirectoryInfo : FSIMode.FileInfo; // Обновляем состояние SelectedMode-а } l.Draw(); // В классе Layer есть метод l.Draw(); Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Open: Enter | Delete: Del | Rename: F4 | Back: Backspace | Exit: Esc"); // Справка Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) { // Используем switch для клавы case ConsoleKey.UpArrow: // Стрелка вверх if (l.SelectedIndex > 0) { // Чтобы не выйти за рамки l.SelectedIndex--; if (l.SelectedIndex < l.Left) { // Ставим границы отрезка l.Left--; l.Right--; } } break; case ConsoleKey.DownArrow: // Стрелка вниз if (l.SelectedIndex < l.Content.Length - 1) { l.SelectedIndex++; if (l.SelectedIndex > l.Right) { // Ставим границы отрезка l.Left++; l.Right++; } } break; case ConsoleKey.Enter: // При нажатии ENTER, есть два вида действия. if (l.Content.Length == 0) // Если текущяя папка пустая, нет смысла нажимать на ENTER! { break; } if (LayerMode == FSIMode.FileInfo) { break; } if (SelectedMode == FSIMode.DirectoryInfo) { // Первое действие - когда выделенный контент это папка, добавляем новый Слой в стек DirectoryInfo dir = l.Content[l.SelectedIndex] as DirectoryInfo; history.Push(new Layer { Content = Combine(dir.GetDirectories(), dir.GetFiles()), SelectedIndex = 0, Left = 0, Right = 20, FileIndex = dir.GetDirectories().Length // начальный индекс файлов }); } else { LayerMode = FSIMode.FileInfo; // Меняем состояние LayerMode на файл using (FileStream fs = new FileStream(l.Content[l.SelectedIndex].FullName, FileMode.Open, FileAccess.Read)) { // будем читать содержимое файла using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; // Белый фон Console.ForegroundColor = ConsoleColor.Black; // Черный шрифт Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Escape: // Выход из программы esc = true; break; case ConsoleKey.Backspace: if (LayerMode == FSIMode.DirectoryInfo) { // Перед выходом определяем состояние LayerMode if (history.Count() > 1) // Граница чтобы не вылететь { history.Pop(); // Удаление Слоя из стека } } else { LayerMode = FSIMode.DirectoryInfo; // При выходе из файла, меняем состояние на папку } break; case ConsoleKey.Delete: if (LayerMode == FSIMode.FileInfo || l.Content.Length == 0) // Ничего не делаем, если находимся в файле или папка пуста { break; } if (SelectedMode == FSIMode.FileInfo) // Перед удалением определяем тип контента { (l.Content[l.SelectedIndex] as FileInfo).Delete(); } else { (l.Content[l.SelectedIndex] as DirectoryInfo).Delete(true); // Truе удаляет папку с файлами } history.Pop(); // удаляем текущий Слой и обновляем if (history.Count == 0) { // Если это первый Слой, берем Слой startPath, и из него записываем startPath = new DirectoryInfo(@"C:\Users\aruzh"); history.Push(new Layer { Content = Combine(startPath.GetDirectories(), startPath.GetFiles()), SelectedIndex = Math.Min(l.SelectedIndex, l.Content.Length - 2), Left = l.Left, Right = l.Right, FileIndex = startPath.GetDirectories().Length }); } else { DirectoryInfo dir = new DirectoryInfo(history.Peek().Content[history.Peek().SelectedIndex].FullName); // Или предыдущий Слой history.Push(new Layer { Content = Combine(dir.GetDirectories(), dir.GetFiles()), SelectedIndex = Math.Min(l.SelectedIndex, l.Content.Length - 2), Left = l.Left, Right = l.Right, FileIndex = dir.GetDirectories().Length }); } break; case ConsoleKey.F4: // Rename if (LayerMode == FSIMode.FileInfo || l.Content.Length == 0) // Ничего не делаем если находимся в файле или папка пуста { break; } string fullname = l.Content[l.SelectedIndex].FullName; // полный путь string name = l.Content[l.SelectedIndex].Name; // имя файла string path = fullname.Remove(fullname.Length - name.Length); // путь без имени Console.WriteLine("Please enter the new name, to rename {0}:", name); // новое имя string newname = Console.ReadLine(); while (newname.Length == 0 || pathExists(path + newname, SelectedMode)) { // проверка наличия пути Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); } if (SelectedMode == FSIMode.DirectoryInfo) // Заменяем с помощью Move { new DirectoryInfo(fullname).MoveTo(path + newname); } else { new FileInfo(fullname).MoveTo(path + newname); } DirectoryInfo di = new DirectoryInfo(path + newname); l.Content[l.SelectedIndex] = di as FileSystemInfo; // Замена директорий break; default: break; } } }
static void Main(string[] args) { DirectoryInfo Dir = new DirectoryInfo(@"C:\Users\Admin\Desktop\Tamirlan"); Lawer l = new Lawer // папкаларды,файлдарды,индексті көрсететін класс құрамыз { DirCon = Dir.GetDirectories(), //DirCon массиві үшін Dir директорясында папканың адресін көрсетеміз FileCon = Dir.GetFiles(), selectedIndex = 0 }; l.Draw(); FSIMode Mod = FSIMode.DirectoryInfo; //папкалар үшін жаңа FSI(enum) құрамыз Stack <Lawer> contral = new Stack <Lawer>(); //жаңа стэк құрамыз contral.Push(l); // стэкке class(l) ді енгіземіз bool work = false; while (!work) { if (Mod == FSIMode.DirectoryInfo) //егер FSI(enum) папка болса { contral.Peek().Draw(); //стэкка Draw функциясын көрсетеміз Console.BackgroundColor = ConsoleColor.Blue; Console.WriteLine("Deleted: Deleted | Rename: R | Back: Bakcspace | Open: Enter"); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo key = Console.ReadKey(); // басылған консолдың клавиштерін сипаттайды switch (key.Key) // { case ConsoleKey.UpArrow: //егер стрелка жоғарыны бассақ if (contral.Peek().selectedIndex > 0) { contral.Peek().selectedIndex--; // қызыл курсор бірінші элементтен жоғары бармайды } break; case ConsoleKey.DownArrow: //егер стрелка төменді бассақ if (contral.Peek().selectedIndex < contral.Peek().DirCon.Length + contral.Peek().FileCon.Length - 1) { contral.Peek().selectedIndex++; //қызыл курсор соңғы элементтен төмен түспейді } break; case ConsoleKey.Enter: // егер Enter-ді бассақ int ind = contral.Peek().selectedIndex; // if (contral.Peek().selectedIndex < contral.Peek().DirCon.Length) //егер ол папканың индексі болса { DirectoryInfo di = contral.Peek().DirCon[contral.Peek().selectedIndex]; //жаңа папка ашамыз сол индекстегі Lawer nl = new Lawer // жаңа класс Lawer-ны құрастырамыз { DirCon = di.GetDirectories(), //Диркон массивіне ди папкысын адресін көрсетеміз FileCon = di.GetFiles(), //Файлкон массивіне ди файлдарының адресін көрсетеміз selectedIndex = 0 }; contral.Push(nl); //стэкка nl класын енгіземіз } else { Mod = FSIMode.File; // Егер FSI(enum) файл болса FileStream fl = new FileStream(contral.Peek().FileCon[contral.Peek().selectedIndex - contral.Peek().DirCon.Length].FullName, FileMode.Open, FileAccess.Read); // файлдың индекстерін аламыз StreamReader sr = new StreamReader(fl); Console.BackgroundColor = ConsoleColor.Black; //файлды қара фонға бояйды Console.ForegroundColor = ConsoleColor.White; //файлдағы ақпаратты ақ түске бояйды Console.Clear(); //барлығын кетіреміз Console.WriteLine(sr.ReadToEnd()); //файлдағы ақпаратты оқимыз сонына дейін fl.Close(); sr.Close(); } break; case ConsoleKey.Backspace: //егер Backspace-ты бассақ if (Mod == FSIMode.DirectoryInfo) //егер FSI(enum) папка болса { contral.Pop(); //бетіндегі консолды толығымен кетіреді } else //егер FSI(enum) файл болса { Mod = FSIMode.DirectoryInfo; //онда файлдың бастапқы папкасын қайтарады } break; case ConsoleKey.Escape: //егер Escape-ты бассақ work = true; //онда консол жұмысын тоқтатады break; case ConsoleKey.Delete: //егер Delete-ты бассақ int index = contral.Peek().selectedIndex; int a = contral.Peek().DirCon.Length; int b = contral.Peek().FileCon.Length; if (index < a) //Егер индекс папканың индексаны келсе { Directory.Delete(contral.Peek().DirCon[index].FullName); //көрсетілген индекстегі папканы кетіреміз } else //Егер индекс файлдың индексаны келіп тұрса { File.Delete(contral.Peek().FileCon[index - a].FullName); //көрсетілген индекстегі файлды кетіреміз } contral.Pop(); //соңғы бөлігін кетіріп ,одан бұрынғы бөлікті шығарады if (contral.Count == 0) //Егер басапқы бөлікте болсақ { Lawer nl = new Lawer //жаңа класс құрамыз { DirCon = Dir.GetDirectories(), // FileCon = Dir.GetFiles(), // selectedIndex = 0 }; contral.Push(nl); //стэкка nl класын енгіземіз } else //егер бастапқы бөлікте болмасақ { DirectoryInfo dif = contral.Peek().DirCon[index]; Lawer nl = new Lawer { DirCon = dif.GetDirectories(), //Диркон массивына диф папкасындағы папкаларды енгіземіз FileCon = dif.GetFiles(), //Диркон массивына диф папкасындағы файлдарды енгіземіз selectedIndex = 0 }; contral.Push(nl); //осыларды стэкка енгіземіз } break; case ConsoleKey.R: //Егерде R-ды бассақ index = contral.Peek().selectedIndex; // a = contral.Peek().DirCon.Length; //папкалардың санын бөлек санға теңестіріп b = contral.Peek().FileCon.Length; //файлдардың санын бөлек санға теңестіріп аламыз string name, fullname; int IndexMode; if (index < a) // Егер индекс папкаға көрсетсе { name = contral.Peek().DirCon[index].Name; //папканың атың строка түрінде оқимыз fullname = contral.Peek().DirCon[index].FullName; //папканың толық атын строка түрінде оқимыз IndexMode = 1; } else { name = contral.Peek().FileCon[index - a].Name; //файлдың атын строка түрінде оқимыз fullname = contral.Peek().FileCon[index - a].FullName; //файлдың толық атын строка түрінде окимыз IndexMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); //ақпартаттың толық атының адресін құрамыз Console.WriteLine("ename: Please to write a new name:"); string newname = Console.ReadLine(); //папка немесе файлдың жаңа атын жазамыз if (IndexMode == 1) //егер ақпарат папка болса { new DirectoryInfo(contral.Peek().DirCon[index].FullName).MoveTo(fullname + newname); //папканы жаңа атымен бірге ауыстырамыз } else { new FileInfo(contral.Peek().FileCon[index - a].FullName).MoveTo(fullname + newname); //файлды жаңа атымен бірге ауыстырамызы } contral.Pop(); //стэктың соңғы элементін кетіреміз if (contral.Count == 0) //егер стэк бос болса { Lawer nl = new Lawer //онда жаңа класс ашып оған бастапқы папканың мәліметтерін теңестіреміз { DirCon = Dir.GetDirectories(), FileCon = Dir.GetFiles(), selectedIndex = 0 }; contral.Push(nl); //және оны стэкка қосамыз } else //егер стэк бос болмаса { DirectoryInfo dif = contral.Peek().DirCon[index]; //онда біз ашқан соңғы папканың мәліметтерін жаңа класс құру арқылы теңестерімез Lawer nl = new Lawer { DirCon = dif.GetDirectories(), FileCon = dif.GetFiles(), selectedIndex = 0 }; contral.Push(nl); } break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Panki\Desktop\for file manager"); Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: int index = history.Peek().SelectedIndex; int a = history.Peek().Content.Length; int b = history.Peek().Content.Length; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: esc = true; break; case ConsoleKey.D: int g = history.Peek().SelectedIndex; FileSystemInfo fg = history.Peek().Content[g]; fg.Delete(); if (history.Count == 0) { history.Peek(); if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } } else if (history.Count > 0) { history.Pop(); int jk = history.Peek().SelectedIndex; FileSystemInfo nb = history.Peek().Content[jk]; DirectoryInfo df = nb as DirectoryInfo; history.Push(new Layer { Content = df.GetFileSystemInfos(), SelectedIndex = 0 }); } break; case ConsoleKey.R: int q = history.Peek().SelectedIndex; FileSystemInfo cv = history.Peek().Content[q]; Console.Clear(); Console.Write("Переименовать в: "); string name = Console.ReadLine(); if (cv.GetType() == typeof(DirectoryInfo)) { Console.ForegroundColor = ConsoleColor.Green; Console.BackgroundColor = ConsoleColor.Black; Directory.Move(cv.FullName, Path.GetDirectoryName(cv.FullName) + "/" + name); } else { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.BackgroundColor = ConsoleColor.Black; File.Copy(cv.FullName, Path.GetDirectoryName(cv.FullName) + "/" + name + ".txt"); File.Delete(cv.FullName); history.Pop(); int lk = history.Peek().SelectedIndex; FileSystemInfo uj = history.Peek().Content[lk]; DirectoryInfo hn = uj as DirectoryInfo; history.Push(new Layer { Content = hn.GetFileSystemInfos(), SelectedIndex = 0 }); } break; } } }
static void Main(string[] args) { DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\c++"); Layer l = new Layer { Directories = directoryInfo.GetDirectories(), Files = directoryInfo.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); FSIMode mode = FSIMode.DIR; while (true) { if (mode == FSIMode.DIR) { history.Peek().Draw(); } ConsoleKeyInfo ConsoleKey = Console.ReadKey(); if (ConsoleKey.Key == System.ConsoleKey.UpArrow) { history.Peek().SelectedIndex--; } else if (ConsoleKey.Key == System.ConsoleKey.DownArrow) { history.Peek().SelectedIndex++; } else if (ConsoleKey.Key == System.ConsoleKey.Enter) { int x = history.Peek().SelectedIndex; if (x < history.Peek().Directories.Length) // opening the folders { DirectoryInfo d = history.Peek().Directories[x]; Layer ly = new Layer { Directories = d.GetDirectories(), Files = d.GetFiles(), SelectedIndex = 0 }; history.Push(ly); } else { mode = FSIMode.FILE; StreamReader sr = new StreamReader(history.Peek().Files[x - history.Peek().Directories.Length].FullName); string s = sr.ReadToEnd(); sr.Close(); Console.BackgroundColor = ConsoleColor.DarkGray; Console.ForegroundColor = ConsoleColor.White; Console.Clear(); Console.WriteLine(s); } } else if (ConsoleKey.Key == System.ConsoleKey.Backspace) { if (mode == FSIMode.DIR) { if (history.Count > 1) { history.Pop(); } } else { mode = FSIMode.DIR; // if it is the file then it returns back to the folder } } else if (ConsoleKey.Key == System.ConsoleKey.Delete) { int delete = history.Peek().SelectedIndex; if (delete < history.Peek().Directories.Length) { history.Peek().Directories[delete].Delete(true); } else { history.Peek().Files[delete - history.Peek().Directories.Length].Delete(); } history.Pop(); // if all layers are closed(i.e. you were in the main directory) if (history.Count() == 0) { Layer lay = new Layer { Directories = directoryInfo.GetDirectories(), Files = directoryInfo.GetFiles(), SelectedIndex = delete-- }; history.Push(lay); } // if you are in subdirectory else { int i = history.Peek().SelectedIndex; DirectoryInfo dd = history.Peek().Directories[i]; Layer ly = new Layer { Directories = dd.GetDirectories(), Files = dd.GetFiles(), SelectedIndex = delete-- }; history.Push(ly); } } else if (ConsoleKey.Key == System.ConsoleKey.R) { Console.Clear(); int rename = history.Peek().SelectedIndex; int i = rename; string name, fullname; int selectedMode; if (rename < history.Peek().Directories.Length) { name = history.Peek().Directories[rename].Name; fullname = history.Peek().Directories[rename].FullName; selectedMode = 1; } else { name = history.Peek().Files[rename - history.Peek().Directories.Length].Name; fullname = history.Peek().Files[rename - history.Peek().Directories.Length].FullName; selectedMode = 2; } string path = fullname.Remove(fullname.Length - name.Length); Console.WriteLine("Please enter the new name and extension of the file if it is necessary"); string newname = Console.ReadLine(); if (selectedMode == 1) { new DirectoryInfo(history.Peek().Directories[rename].FullName).MoveTo(path + newname); } else { new FileInfo(history.Peek().Files[rename - history.Peek().Directories.Length].FullName).MoveTo(path + newname); } history.Pop(); if (history.Count == 0) { Layer lay = new Layer { Directories = directoryInfo.GetDirectories(), Files = directoryInfo.GetFiles(), SelectedIndex = i }; history.Push(lay); } else { rename = history.Peek().SelectedIndex; DirectoryInfo dir = history.Peek().Directories[rename]; Layer ly = new Layer { Directories = dir.GetDirectories(), Files = dir.GetFiles(), SelectedIndex = i }; history.Push(ly); } } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\test"); //implying the path Layer l = new Layer { Items = dir.GetFileSystemInfos(), //making exemplar whose argument is Items and SelectedItemIndex SelectedItemIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; //making variable curMode whose тип данные FSIMode Stack <Layer> history = new Stack <Layer>(); //creating the stack history.Push(l); bool quit = false; while (!quit) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); //calling the function } ConsoleKeyInfo pressedKey = Console.ReadKey(); if (pressedKey.Key == ConsoleKey.UpArrow) { history.Peek().SelectedItemIndex--; } //results of pressedkeys else if (pressedKey.Key == ConsoleKey.DownArrow) { history.Peek().SelectedItemIndex++; } else if (pressedKey.Key == ConsoleKey.Enter) { int index = history.Peek().SelectedItemIndex; FileSystemInfo fsi = history.Peek().Items[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; // DirectoryInfo d = (DirectoryInfo)fsi; DirectoryInfo d = fsi as DirectoryInfo; //if it is directory, showing content history.Push(new Layer { Items = d.GetFileSystemInfos(), SelectedItemIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; //if it is file, showing content Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } } else if (pressedKey.Key == ConsoleKey.Delete) { int x2 = history.Peek().SelectedItemIndex; FileSystemInfo fileSystemInfo2 = history.Peek().Items[x2]; if (fileSystemInfo2.GetType() == typeof(DirectoryInfo)) { DirectoryInfo d = fileSystemInfo2 as DirectoryInfo; Directory.Delete(fileSystemInfo2.FullName, true); history.Peek().Items = d.Parent.GetFileSystemInfos(); } else { FileInfo f = fileSystemInfo2 as FileInfo; File.Delete(fileSystemInfo2.FullName); history.Peek().Items = f.Directory.GetFileSystemInfos(); } history.Peek().SelectedItemIndex--; } else if (pressedKey.Key == ConsoleKey.F6) { Console.BackgroundColor = ConsoleColor.Black; Console.Clear(); string name = Console.ReadLine(); int x3 = history.Peek().SelectedItemIndex; FileSystemInfo fileSystemInfo3 = history.Peek().Items[x3]; if (fileSystemInfo3.GetType() == typeof(DirectoryInfo)) { DirectoryInfo directoryInfo = fileSystemInfo3 as DirectoryInfo; Directory.Move(fileSystemInfo3.FullName, directoryInfo.Parent + "/" + name); history.Peek().Items = directoryInfo.Parent.GetFileSystemInfos(); } else { FileInfo fileInfo = fileSystemInfo3 as FileInfo; File.Move(fileSystemInfo3.FullName, fileInfo.Directory.FullName + "/" + name); history.Peek().Items = fileInfo.Directory.GetFileSystemInfos(); } } else if (pressedKey.Key == ConsoleKey.Backspace) { if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } } else if (pressedKey.Key == ConsoleKey.Escape) { quit = true; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Week2"); if (!dir.Exists) { Console.WriteLine("Directory doesn't exist"); return; } Layer l = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; FSIMode mode = FSIMode.DIrectoryInfo; while (!esc) { if (mode == FSIMode.DIrectoryInfo) { history.Peek().Print(); Console.ForegroundColor = ConsoleColor.White; Console.BackgroundColor = ConsoleColor.Black; } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: if (history.Peek().SelectedIndex > 0) { history.Peek().SelectedIndex--; } else { history.Peek().SelectedIndex = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; } break; case ConsoleKey.DownArrow: if ((history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1) > history.Peek().SelectedIndex) { history.Peek().SelectedIndex++; } else { history.Peek().SelectedIndex = 0; } break; case ConsoleKey.Enter: if ((history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) { break; } int index = history.Peek().SelectedIndex; if (index < history.Peek().DirectoryContent.Length) { DirectoryInfo di = history.Peek().DirectoryContent[index]; history.Push(new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = 0 }); } else { mode = FSIMode.File; using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: if (mode == FSIMode.DIrectoryInfo) { if (history.Count > 1) { history.Pop(); } } else { mode = FSIMode.DIrectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Escape: esc = true; break; case ConsoleKey.Delete: if (mode != FSIMode.DIrectoryInfo || (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) { break; } index = history.Peek().SelectedIndex; int item = index; if (index < history.Peek().DirectoryContent.Length) { history.Peek().DirectoryContent[index].Delete(true); } else { history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete(); } int numOfFSI = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2; history.Pop(); if (history.Count == 0) { Layer l1 = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numOfFSI, 0), item) }; history.Push(l1); } else { index = history.Peek().SelectedIndex; DirectoryInfo d = history.Peek().DirectoryContent[index]; Layer l1 = new Layer { DirectoryContent = d.GetDirectories(), FileContent = d.GetFiles(), SelectedIndex = Math.Min(Math.Max(numOfFSI, 0), item) }; history.Push(l1); } break; case ConsoleKey.F2: if ((history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) { break; } index = history.Peek().SelectedIndex; string name, fullname; int selectedMode; if (index < history.Peek().DirectoryContent.Length) { name = history.Peek().DirectoryContent[index].Name; fullname = history.Peek().DirectoryContent[index].FullName; selectedMode = 1; } else { name = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name; fullname = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); Console.WriteLine("Please enter the new name, to rename {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); while (newname.Length == 0 || PathExists(fullname + newname, selectedMode)) { Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); } Console.WriteLine(selectedMode); if (selectedMode == 1) { new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); } else { new FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); } index = history.Peek().SelectedIndex; item = index; numOfFSI = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; history.Pop(); if (history.Count == 0) { Layer l1 = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numOfFSI, 0), item) }; history.Push(l1); } else { index = history.Peek().SelectedIndex; DirectoryInfo d1 = history.Peek().DirectoryContent[index]; Layer l1 = new Layer { DirectoryContent = d1.GetDirectories(), FileContent = d1.GetFiles(), SelectedIndex = Math.Min(Math.Max(numOfFSI, 0), item) }; history.Push(l1); } break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\test"); Layer l = new Layer { Items = dir.GetFileSystemInfos(), SelectedItemIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool quit = false; while (!quit) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); } ConsoleKeyInfo pressedKey = Console.ReadKey(); if (pressedKey.Key == ConsoleKey.UpArrow) { history.Peek().SelectedItemIndex--; } else if (pressedKey.Key == ConsoleKey.DownArrow) { history.Peek().SelectedItemIndex++; } else if (pressedKey.Key == ConsoleKey.Enter) { //int x = history.Peek().SelectedItemIndex; //DirectoryInfo y = history.Peek().Items[x] as DirectoryInfo; //history.Push(new Layer(y.GetFileSystemInfos())); int index = history.Peek().SelectedItemIndex; FileSystemInfo fsi = history.Peek().Items[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; // DirectoryInfo d = (DirectoryInfo)fsi; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Items = d.GetFileSystemInfos(), SelectedItemIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } } else if (pressedKey.Key == ConsoleKey.Backspace) { if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } } else if (pressedKey.Key == ConsoleKey.Escape) { quit = true; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(Console.ReadLine()); // read way to our directory Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; //Select directory mode Stack <Layer> history = new Stack <Layer>(); //Create stack where we push our directory history.Push(l); bool esc = false; while (!esc) // while true { if (curMode == FSIMode.DirectoryInfo) //if we in directory we will show all files and directory in selected directory { history.Peek().Show(); } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: //select upper file or directory history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: //select lower file or directory history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: //go in file or directory3 int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; // creat new info in directory or file if (fsi.GetType() == typeof(DirectoryInfo)) //we push all file and directory in selected directory, then push in stack { curMode = FSIMode.DirectoryInfo; //select directory mode DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); } else //we write all text in file { curMode = FSIMode.File; StreamReader sr = new StreamReader(fsi.FullName); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); //write all texts in file } break; case ConsoleKey.Backspace: // back to previous directory or close file if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ResetColor(); } break; case ConsoleKey.Delete: //Delete selecte file or Directory history.Peek().Delete(); break; case ConsoleKey.Tab: history.Peek().Rename(); break; case ConsoleKey.Escape: esc = true; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\aknur\Desktop\CN"); //the path Layer l = new Layer //the layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); //creating stack of layher history.Push(l); //pushing the layer bool esc = false; //boolean false while (!esc) //while func which ends if esc is false { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); Console.ForegroundColor = ConsoleColor.Red; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("\nDelete: Del Rename: F4"); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) //switch case to bind keys to some functions as like if func { case ConsoleKey.UpArrow: //up arrow selected index decreases therefore it goes upwards history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: //same as up arrow but increase history.Peek().SelectedIndex++; break; case ConsoleKey.Enter: //enter button int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) //identifyes is selected index is file or directory { curMode = FSIMode.DirectoryInfo; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); //pushing new layer } else { curMode = FSIMode.File; //if file it opens it using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) //reads and makes chance to edit file { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: //back space if (curMode == FSIMode.DirectoryInfo) { history.Pop(); //just pops the layer back } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Delete: //delete file or folder int indexDel = history.Peek().SelectedIndex; FileSystemInfo fsiDel = history.Peek().Content[indexDel]; if (fsiDel.GetType() == typeof(DirectoryInfo)) //finds if folder of file { string pathDel = fsiDel.FullName; Directory.Delete(pathDel, true); //delets } else { string pathFile = fsiDel.FullName; File.Delete(pathFile); //delets } history.Push(new Layer //push as new layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }); break; case ConsoleKey.F4: //rename the file or folder the same as delete Console.Clear(); int indexReName = history.Peek().SelectedIndex; FileSystemInfo fsiReName = history.Peek().Content[indexReName]; string pathRename = Console.ReadLine(); string path1 = dir + @"\" + fsiReName; string path2 = dir + @"\" + pathRename; if (fsiReName.GetType() == typeof(DirectoryInfo)) { Directory.Move(path1, path2); } else { File.Move(path1, path2); } history.Push(new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }); break; case ConsoleKey.Escape: //escape turns the esc true then the program stops esc = true; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Test"); //берем тестовую папку Layer l = new Layer { DirContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool exit = false; FSIMode curMode = FSIMode.DirectoryInfo; while (!exit) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) { case ConsoleKey.UpArrow: history.Peek().SelectedIndex--; break; case ConsoleKey.DownArrow: history.Peek().SelectedIndex++; //вверх, вниз думаю понятно break; case ConsoleKey.Enter: if (history.Peek().DirContent.Length + history.Peek().FileContent.Length == 0) //игнор при пустом экране { break; } int index = history.Peek().SelectedIndex; if (index < history.Peek().DirContent.Length) // если папка (у нас же сортированный список) { DirectoryInfo d = history.Peek().DirContent[index]; history.Push(new Layer { DirContent = d.GetDirectories(), FileContent = d.GetFiles(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirContent.Length].FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) //если файл, то открываем, читаем { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: // назад if (curMode == FSIMode.DirectoryInfo) //из папаки { if (history.Count > 1) { history.Pop(); } } else { curMode = FSIMode.DirectoryInfo; //из файла Console.ForegroundColor = ConsoleColor.White; //возвращаем обычный цвет } break; case ConsoleKey.Escape: exit = true; break; case ConsoleKey.Delete: if (curMode != FSIMode.DirectoryInfo || (history.Peek().DirContent.Length + history.Peek().FileContent.Length) == 0) { break; } index = history.Peek().SelectedIndex; int ind = index; if (index < history.Peek().DirContent.Length) { history.Peek().DirContent[index].Delete(true); //если папка, то удаляем и то, что внутри } else { history.Peek().FileContent[index - history.Peek().DirContent.Length].Delete(); // если файл, то просто дел } int numofcontent = history.Peek().DirContent.Length + history.Peek().FileContent.Length - 2; //сколько элементов осталось history.Pop(); //чтобы обновился экран if (history.Count == 0) { Layer nl = new Layer { DirContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); //даже если мы все удалили он не вылетает назад } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirContent[index]; Layer nl = new Layer { DirContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; case ConsoleKey.F6: if (history.Peek().DirContent.Length + history.Peek().FileContent.Length == 0) { break; } index = history.Peek().SelectedIndex; string name, fullname; int selectedMode; if (index < history.Peek().DirContent.Length) { name = history.Peek().DirContent[index].Name; fullname = history.Peek().DirContent[index].FullName; selectedMode = 1; } else { name = history.Peek().FileContent[index - history.Peek().DirContent.Length].Name; fullname = history.Peek().FileContent[index - history.Peek().DirContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); //удаляем имя,чтобы дать новое Console.WriteLine("New name for {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); Console.WriteLine(selectedMode); if (selectedMode == 1) { new DirectoryInfo(history.Peek().DirContent[index].FullName).MoveTo(fullname + newname); //переименовали } //П.С. по идее заменили else { new FileInfo(history.Peek().FileContent[index - history.Peek().DirContent.Length].FullName).MoveTo(fullname + newname); } index = history.Peek().SelectedIndex; ind = index; numofcontent = history.Peek().DirContent.Length + history.Peek().FileContent.Length - 1; history.Pop(); if (history.Count == 0) { Layer nl = new Layer { DirContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirContent[index]; Layer nl = new Layer { DirContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; default: break; } } }
static void Main(string[] args) { DirectoryInfo Dir = new DirectoryInfo(@"C:\Users\Admin\Desktop\Tamirlan"); Lawer l = new Lawer // папкаларды,файлдарды,индексті көрсететін класс құрамыз { DirCon = Dir.GetDirectories(), //DirCon массиві үшін Dir директорясында папканың адресін көрсетеміз FileCon = Dir.GetFiles(), selectedIndex = 0 }; l.Draw(); FSIMode Mod = FSIMode.DirectoryInfo; //папкалар үшін жаңа FSI(enum) құрамыз Stack <Lawer> contral = new Stack <Lawer>(); //жаңа стэк құрамыз contral.Push(l); // стэкке class(l) ді енгіземіз bool work = false; while (!work) { if (Mod == FSIMode.DirectoryInfo) //егер FSI(enum) папка болса { contral.Peek().Draw(); //стэкка Draw функциясын көрсетеміз } ConsoleKeyInfo key = Console.ReadKey(); // басылған консолдың клавиштерін сипаттайды switch (key.Key) // { case ConsoleKey.UpArrow: //егер стрелка жоғарыны бассақ if (contral.Peek().selectedIndex > 0) { contral.Peek().selectedIndex--; // қызыл курсор бірінші элементтен жоғары бармайды } break; case ConsoleKey.DownArrow: //егер стрелка төменді бассақ if (contral.Peek().selectedIndex < contral.Peek().DirCon.Length + contral.Peek().FileCon.Length - 1) { contral.Peek().selectedIndex++; //қызыл курсор соңғы элементтен төмен түспейді } break; case ConsoleKey.Enter: // егер Enter-ді бассақ int ind = contral.Peek().selectedIndex; // if (contral.Peek().selectedIndex < contral.Peek().DirCon.Length) //егер ол папканың индексі болса { DirectoryInfo di = contral.Peek().DirCon[contral.Peek().selectedIndex]; //жаңа папка ашамыз сол индекстегі Lawer nl = new Lawer // жаңа класс Lawer-ны құрастырамыз { DirCon = di.GetDirectories(), //Диркон массивіне ди папкысын адресін көрсетеміз FileCon = di.GetFiles(), //Файлкон массивіне ди файлдарының адресін көрсетеміз selectedIndex = 0 }; contral.Push(nl); //стэкка nl класын енгіземіз } else { Mod = FSIMode.File; // Егер FSI(enum) файл болса FileStream fl = new FileStream(contral.Peek().FileCon[contral.Peek().selectedIndex - contral.Peek().DirCon.Length].FullName, FileMode.Open, FileAccess.Read); // файлдың индекстерін аламыз StreamReader sr = new StreamReader(fl); Console.BackgroundColor = ConsoleColor.Black; //файлды қара фонға бояйды Console.ForegroundColor = ConsoleColor.White; //файлдағы ақпаратты ақ түске бояйды Console.Clear(); //барлығын кетіреміз Console.WriteLine(sr.ReadToEnd()); //файлдағы ақпаратты оқимыз сонына дейін fl.Close(); sr.Close(); } break; case ConsoleKey.Backspace: //егер Backspace-ты бассақ if (Mod == FSIMode.DirectoryInfo) //егер FSI(enum) папка болса { contral.Pop(); //бетіндегі консолды толығымен кетіреді } else //егер FSI(enum) файл болса { Mod = FSIMode.DirectoryInfo; //онда файлдың бастапқы папкасын қайтарады } break; case ConsoleKey.Escape: //егер Escape-ты бассақ work = true; //онда консол жұмысын тоқтатады break; } } }
static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo(@"C:\Users\user\Desktop\PP2lab3"); Layer l = new Layer { Directories = di.GetDirectories(), Files = di.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool x = false; FSIMode md = FSIMode.Folder; while (!x) { if (md == FSIMode.Folder) { history.Peek().Draw(); } ConsoleKeyInfo ifkey = Console.ReadKey(); if (ifkey.Key == ConsoleKey.UpArrow) { history.Peek().SelectedIndex--; } else if (ifkey.Key == ConsoleKey.DownArrow) { history.Peek().SelectedIndex++; } else if (ifkey.Key == ConsoleKey.Enter) { int open = history.Peek().SelectedIndex; if (open < history.Peek().Directories.Length) { DirectoryInfo dd = history.Peek().Directories[open]; Layer lay = new Layer { Directories = dd.GetDirectories(), Files = dd.GetFiles(), SelectedIndex = 0 }; history.Push(lay); } else { md = FSIMode.File; StreamReader sr = new StreamReader(history.Peek().Files[open - history.Peek().Directories.Length].FullName); string s = sr.ReadToEnd(); sr.Close(); Console.BackgroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.DarkBlue; Console.Clear(); Console.WriteLine(s); } } else if (ifkey.Key == ConsoleKey.Backspace) { if (md == FSIMode.Folder) { if (history.Count > 1) { history.Pop(); } } else { md = FSIMode.Folder; } } else if (ifkey.Key == ConsoleKey.Delete) { int del = history.Peek().SelectedIndex; int z = del; if (del < history.Peek().Directories.Length) { history.Peek().Directories[del].Delete(true); } else { history.Peek().Files[del - history.Peek().Directories.Length].Delete(); } history.Pop(); if (history.Count() == 0) { Layer lay = new Layer { Directories = di.GetDirectories(), Files = di.GetFiles(), SelectedIndex = z-- }; history.Push(lay); } else { int i = history.Peek().SelectedIndex; DirectoryInfo dd = history.Peek().Directories[i]; Layer ly = new Layer { Directories = dd.GetDirectories(), Files = dd.GetFiles(), SelectedIndex = z-- }; history.Push(ly); } } else if (ifkey.Key == ConsoleKey.F2) { Console.Clear(); int rename = history.Peek().SelectedIndex; int i = rename; string name, fname; int selMode; if (rename < history.Peek().Directories.Length) { name = history.Peek().Directories[rename].Name; fname = history.Peek().Directories[rename].FullName; selMode = 1; } else { name = history.Peek().Files[rename - history.Peek().Directories.Length].Name; fname = history.Peek().Files[rename - history.Peek().Directories.Length].FullName; selMode = 2; } string path = fname.Remove(fname.Length - name.Length); Console.WriteLine("Please, enter the new name with it extension:"); string newname = Console.ReadLine(); if (selMode == 1) { new DirectoryInfo(history.Peek().Directories[rename].FullName).MoveTo(path + newname); } else { new FileInfo(history.Peek().Files[rename - history.Peek().Directories.Length].FullName).MoveTo(path + newname); } history.Pop(); if (history.Count == 0) { Layer lay = new Layer { Directories = di.GetDirectories(), Files = di.GetFiles(), SelectedIndex = i }; history.Push(lay); } else { rename = history.Peek().SelectedIndex; DirectoryInfo dir = history.Peek().Directories[rename]; Layer ly = new Layer { Directories = dir.GetDirectories(), Files = dir.GetFiles(), SelectedIndex = i }; history.Push(ly); } } else if (ifkey.Key == ConsoleKey.Escape) { x = true; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\asus-\source\repos\test"); //первоначальная директория layer l = new layer //создаем слой { Content = Combine(dir.GetDirectories(), dir.GetFiles()), SelectedIndex = 0 }; Stack <layer> history = new Stack <layer>(); //в стэке будем хранить слои history.Push(l); //первоначальную директорию закидываем в стэк bool esc = false; FSIMode curMode = FSIMode.DirectoryInfo; //текущее состояние в начале будет папкой while (!esc) { if (curMode == FSIMode.DirectoryInfo) { history.Peek().Draw(); //рисуем последний слой } l = history.Peek(); //начальную директорию = последний слой ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); //читаем с клавиш switch (consoleKeyInfo.Key) { case ConsoleKey.Backspace: //кнопка назад if (curMode == FSIMode.DirectoryInfo) { if (history.Count > 1) { history.Pop(); //возвращаемся назад } } else { //если это папка возвращаемся в папку с этим файлом curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Enter: //кнопка Enter if (history.Peek().Content.Length == 0) //если пуст внутренний контент { break; } int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { //проверяем под выбранный индекс чем является папка или файл. Если папка, то открываем под новый слой и рисуем по новому DirectoryInfo d = fsi as DirectoryInfo; history.Push(new layer { Content = Combine(d.GetDirectories(), d.GetFiles()), SelectedIndex = 0 }); } else { //условие если это файл. Используем потокового читателя, чтобы прочитать информацию и переписать всё то, что написано в файле curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.UpArrow: //кнопка вверх if (history.Peek().SelectedIndex > 0) { history.Peek().SelectedIndex--; } break; case ConsoleKey.Delete: //кнопка удалить //условие когда кнопка не работает if (curMode == FSIMode.File || l.Content.Length == 0) { break; } //условие если это выбранный объект это файл if (l.Content[l.SelectedIndex].GetType() == typeof(FileInfo)) { l.Content[l.SelectedIndex].Delete(); } //или папка else { (l.Content[l.SelectedIndex] as DirectoryInfo).Delete(true); } history.Pop(); //возвращаемся на предыдущий слой if (history.Count == 0) //если больше нет слоев , то возвращаемся на первоначальный { dir = new DirectoryInfo(@"C:\Users\asus-\source\repos\test"); } else //или предыдущий { dir = new DirectoryInfo(history.Peek().Content[history.Peek().SelectedIndex].FullName); } //перерисовываем с уже удаленным объектом history.Push(new layer { Content = Combine(dir.GetDirectories(), dir.GetFiles()), SelectedIndex = Math.Min(l.SelectedIndex, l.Content.Length - 2) }); break; case ConsoleKey.F4: //переименование if (curMode == FSIMode.File || l.Content.Length == 0) { //условие, когда кнопка не будет работать break; } string fullname = l.Content[l.SelectedIndex].FullName; //полное имя выбранного объекта string path = fullname.Remove(fullname.Length - l.Content[l.SelectedIndex].Name.Length); //путь к выбранному объекту Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Enter new name: "); string newname = Console.ReadLine(); //новое имя для объекта while (newname.Length == 0 || Directory.Exists(path + newname)) { Console.WriteLine("This directory is exist, Create new one: "); newname = Console.ReadLine(); } if (l.Content[l.SelectedIndex].GetType() == typeof(DirectoryInfo)) { //процесс переименовки папки new DirectoryInfo(fullname).MoveTo(path + newname); history.Peek().Content[l.SelectedIndex] = new DirectoryInfo(path + newname); } else { //процесс переименовки файла new FileInfo(fullname).MoveTo(path + newname); history.Peek().Content[l.SelectedIndex] = new FileInfo(path + newname); } break; case ConsoleKey.DownArrow: //кнопка вниз if (history.Peek().Content.Length - 1 > history.Peek().SelectedIndex) { history.Peek().SelectedIndex++; } break; case ConsoleKey.Escape: //кнопка выхода из программы esc = true; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\pp1"); // указываем путь if (!dir.Exists) // если файл не существует то выводится следуйщее сообщение { Console.WriteLine("Directory not exist"); return; } Layer l = new Layer // создается ноый слой, которому передаются ниже указынные параметры { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); // создает память пути history.Push(l); // передаем все в слой bool esc = false; // заводим булиновую переменную FSIMode curMode = FSIMode.DirectoryInfo; while (!esc) // пока не вышли { if (curMode == FSIMode.DirectoryInfo) // создаем метод с параметрами { history.Peek().Draw(); Console.ForegroundColor = ConsoleColor.Blue; Console.BackgroundColor = ConsoleColor.Black; Console.WriteLine("Delete: Del | Rename: F2 | Back: Backspace | Exit: Esc"); Console.ForegroundColor = ConsoleColor.White; } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); switch (consolekeyInfo.Key) // набор через клавиатуру { case ConsoleKey.UpArrow: if (history.Peek().SelectedIndex > 0) { history.Peek().SelectedIndex--; } break; case ConsoleKey.DownArrow: if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1 > history.Peek().SelectedIndex) { history.Peek().SelectedIndex++; } break; case ConsoleKey.Enter: if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) { break; } int index = history.Peek().SelectedIndex; if (index < history.Peek().DirectoryContent.Length) { DirectoryInfo d = history.Peek().DirectoryContent[index]; history.Push(new Layer { DirectoryContent = d.GetDirectories(), FileContent = d.GetFiles(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) // читаем фолдер по указанному пути { using (StreamReader sr = new StreamReader(fs)) // делаем читабелным через СтримРидер { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: // через кнопку назад уходим на вверх if (curMode == FSIMode.DirectoryInfo) { if (history.Count > 1) { history.Pop(); } } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; //красим в тот же цвет } break; case ConsoleKey.Escape: esc = true; //выходим из программы через буленувую функцию break; case ConsoleKey.Delete: // удаляет указанный файл или папку if (curMode != FSIMode.DirectoryInfo || (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length) == 0) { break; } index = history.Peek().SelectedIndex; int ind = index; if (index < history.Peek().DirectoryContent.Length) { history.Peek().DirectoryContent[index].Delete(true); // папка удалится в любом случае } else { history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Delete(); } int numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 2; history.Pop(); // история обнавляется if (history.Count == 0) // в случае когда истоиия == 0 { Layer nl = new Layer // новый слой с другими парметрами { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); // история обнавляется } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; case ConsoleKey.F2: // переиминовка файла или папки if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length == 0) { break; } index = history.Peek().SelectedIndex; string name, fullname; int selectedMode; if (index < history.Peek().DirectoryContent.Length) { name = history.Peek().DirectoryContent[index].Name; fullname = history.Peek().DirectoryContent[index].FullName; selectedMode = 1; } else { name = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].Name; fullname = history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName; selectedMode = 2; } fullname = fullname.Remove(fullname.Length - name.Length); // прозьюа переиминовать после нажании F2 Console.WriteLine("Please enter the new name, to rename {0}:", name); Console.WriteLine(fullname); string newname = Console.ReadLine(); while (newname.Length == 0 || pathExists(fullname + newname, selectedMode)) // если названия reapit { Console.WriteLine("This directory was created, Enter the new one"); newname = Console.ReadLine(); } Console.WriteLine(selectedMode); if (selectedMode == 1) { new DirectoryInfo(history.Peek().DirectoryContent[index].FullName).MoveTo(fullname + newname); } else { new FileInfo(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName).MoveTo(fullname + newname); } index = history.Peek().SelectedIndex; ind = index; numofcontent = history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1; history.Pop(); if (history.Count == 0) { Layer nl = new Layer { DirectoryContent = dir.GetDirectories(), FileContent = dir.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); // обнавляется история } else { index = history.Peek().SelectedIndex; DirectoryInfo di = history.Peek().DirectoryContent[index]; Layer nl = new Layer { DirectoryContent = di.GetDirectories(), FileContent = di.GetFiles(), SelectedIndex = Math.Min(Math.Max(numofcontent, 0), ind) }; history.Push(nl); } break; default: // в любом не понятном случае break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Nurik\Desktop\pp2"); Layer l = new Layer { Content = dir.GetFileSystemInfos(), SelectedIndex = 0 }; FSIMode curMode = FSIMode.DirectoryInfo; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool esc = false; while (!esc) { history.Peek().Draw(); ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(); switch (consoleKeyInfo.Key) { case ConsoleKey.UpArrow: //Up if (history.Peek().SelectedIndex == 0) { history.Peek().SelectedIndex = history.Peek().Content.Length - 1; } else { history.Peek().SelectedIndex--; } break; case ConsoleKey.DownArrow: //Down if (history.Peek().SelectedIndex == history.Peek().Content.Length - 1) { history.Peek().SelectedIndex = 0; } else { history.Peek().SelectedIndex++; } break; case ConsoleKey.Enter: //Inside int index = history.Peek().SelectedIndex; FileSystemInfo fsi = history.Peek().Content[index]; if (fsi.GetType() == typeof(DirectoryInfo)) { curMode = FSIMode.DirectoryInfo; DirectoryInfo d = fsi as DirectoryInfo; history.Push(new Layer { Content = d.GetFileSystemInfos(), SelectedIndex = 0 }); } else { curMode = FSIMode.File; using (FileStream fs = new FileStream(fsi.FullName, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(sr.ReadToEnd()); } } } break; case ConsoleKey.Backspace: //Back if (curMode == FSIMode.DirectoryInfo) { history.Pop(); } else { curMode = FSIMode.DirectoryInfo; Console.ForegroundColor = ConsoleColor.White; } break; case ConsoleKey.Delete: //Remove int iter = history.Peek().SelectedIndex; FileSystemInfo fsi1 = history.Peek().Content[iter]; Console.Clear(); Console.WriteLine("Do you want to delete {0} ?\nPress [Y/N]", fsi1.Name); ConsoleKeyInfo res = Console.ReadKey(); while (res.Key != ConsoleKey.Y && res.Key != ConsoleKey.N) { res = Console.ReadKey(); } if (res.Key == ConsoleKey.Y) { fsi1.Delete(); } else { break; } history.Pop(); break; case ConsoleKey.Insert: //Rename int iter1 = history.Peek().SelectedIndex; FileSystemInfo fsi2 = history.Peek().Content[iter1]; Console.WriteLine("Enter new name:"); string name = Console.ReadLine(); string prev = fsi2.FullName; string newName = Path.Combine(Path.GetDirectoryName(prev), name); Directory.Move(prev, newName); history.Pop(); break; case ConsoleKey.Escape: //Exit esc = true; break; } } }
static void Main(string[] args) { DirectoryInfo dir = new DirectoryInfo(@"C:\Users\aruzh\source\repos"); //создает обЪект класса DirectoryInfo по указанному пути Layer l = new Layer // создает объект класса layer { DirectoryContent = dir.GetDirectories(), //заполняет массив методом который возвращает массив с папками FileContent = dir.GetFiles(), //заполняет массив который возвращает массив с файлами SelectedIndex = 0//приваевает выбраному индексу число 0 }; l.Draw(); //вызывает мтода который выводит на консоли папки и файлы Stack <Layer> history = new Stack <Layer>(); //создает стек history.Push(l); //добвляет в конец стека обЪект класса layer bool esc = false; //создает переменную bool и присваивает значение ложь FSIMode curMode = FSIMode.DirectoryInfo; //создает энум созначение каталогов while (!esc) //цикл пока esc = ложь { if (curMode == FSIMode.DirectoryInfo) //если энум директория { history.Peek().Draw(); //то рисует все папки и файлы } ConsoleKeyInfo consolekeyInfo = Console.ReadKey(); // spravo4nik //запрашивает у пользователя нажатии клавиши switch (consolekeyInfo.Key) //проверяет нажатые клавиши { case ConsoleKey.UpArrow: //если клавиша вверх создана if (history.Peek().SelectedIndex > 0) //проверяет если выбранный файл или папка не в вверху { history.Peek().SelectedIndex--; //то поднимает выбранный индекс путем декримента } break; case ConsoleKey.DownArrow: //если клавища нажата вниз if (history.Peek().DirectoryContent.Length + history.Peek().FileContent.Length - 1 > history.Peek().SelectedIndex) //проверяет если индекс выбранного файла или папки меньше общего количества папок и файлов { history.Peek().SelectedIndex++; //понижает выбор вниз путем инкремена выбранного индекса } break; case ConsoleKey.Enter: //если нажата клавиша интер if (history.Peek().DirectoryContent.Length + history.Peek(). FileContent.Length == 0) //если файлов и папок нету то выходит { break; } int index = history.Peek().SelectedIndex; //если нет, то с верхнего элеиента стэка вытаскивает переменную выбранного индекса if (index < history.Peek().DirectoryContent.Length) //если выбранный индекс на папке { DirectoryInfo d = history.Peek().DirectoryContent[index]; //получает инфо о выбранном каталоге history.Push(new Layer // записывает в стек след элемент класс layer { DirectoryContent = d.GetDirectories(), //папки FileContent = d.GetFiles(), //файла SelectedIndex = 0 //выбранный индекс }); } else //если выбранный элемент файл { curMode = FSIMode.File; //меняет энум на файл using (FileStream fs = new FileStream(history.Peek().FileContent[index - history.Peek().DirectoryContent.Length].FullName, FileMode.Open, FileAccess.Read)) { //использует поток для получения содержания выранного файла using (StreamReader sr = new StreamReader(fs)) { //поток для считываения информации с файла Console.BackgroundColor = ConsoleColor.White; //меняте цвет консоли на белый Console.ForegroundColor = ConsoleColor.Black; //меняет цвет текста консоле на черный Console.Clear(); //отчищает консоль Console.WriteLine(sr.ReadToEnd()); //пишет в консоль содержания файла } } } break; case ConsoleKey.Backspace: //если нажата клавища назад if (curMode == FSIMode.DirectoryInfo) //проверяет если мы в папке { if (history.Count > 1) //проверяет если стек хранит больше 1 элемента { history.Pop(); //удаляет верхний элемент стека } } else { curMode = FSIMode.DirectoryInfo; //если мы в файле Console.ForegroundColor = ConsoleColor.White; //меняет цвет текста консоли на белый } break; case ConsoleKey.Escape: //если нажата клава еск esc = true; //меняет перменную на истину и закрывается цикл break; default: break; } } }
static void Main(string[] args) { DirectoryInfo firstdir = new DirectoryInfo(@"C:\Users\hp\Desktop\test"); Layer l = new Layer { Directories = firstdir.GetDirectories(), Files = firstdir.GetFiles(), SelectedIndex = 0 }; Stack <Layer> history = new Stack <Layer>(); history.Push(l); bool quit = false; FSIMode mode = FSIMode.Folder; while (!quit) { if (mode == FSIMode.Folder) { history.Peek().Draw(); } ConsoleKeyInfo key = Console.ReadKey(); if (key.Key == ConsoleKey.UpArrow) { history.Peek().SelectedIndex--; } else if (key.Key == ConsoleKey.DownArrow) { history.Peek().SelectedIndex++; } else if (key.Key == ConsoleKey.Enter) { int newopen = history.Peek().SelectedIndex; if (newopen < history.Peek().Directories.Length) { DirectoryInfo d = history.Peek().Directories[newopen]; Layer ly = new Layer { Directories = d.GetDirectories(), Files = d.GetFiles(), SelectedIndex = 0 }; history.Push(ly); } else { mode = FSIMode.File; StreamReader sr = new StreamReader(history.Peek().Files[newopen - history.Peek().Directories.Length].FullName); string s = sr.ReadToEnd(); sr.Close(); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); Console.WriteLine(s); } } else if (key.Key == ConsoleKey.Backspace) { if (mode == FSIMode.Folder) { if (history.Count > 1) { history.Pop(); } } else { mode = FSIMode.Folder; } } else if (key.Key == ConsoleKey.Delete) { int todelete = history.Peek().SelectedIndex; int j = todelete; if (todelete < history.Peek().Directories.Length) { history.Peek().Directories[todelete].Delete(true); } else { history.Peek().Files[todelete - history.Peek().Directories.Length].Delete(); } history.Pop(); if (history.Count() == 0) { Layer lay = new Layer { Directories = firstdir.GetDirectories(), Files = firstdir.GetFiles(), SelectedIndex = j-- }; history.Push(lay); } else { int i = history.Peek().SelectedIndex; DirectoryInfo dd = history.Peek().Directories[i]; Layer ly = new Layer { Directories = dd.GetDirectories(), Files = dd.GetFiles(), SelectedIndex = j-- }; history.Push(ly); } } else if (key.Key == ConsoleKey.R) { Console.Clear(); int torename = history.Peek().SelectedIndex; int i = torename; string name, fullname; int selectedMode; if (torename < history.Peek().Directories.Length) { name = history.Peek().Directories[torename].Name; fullname = history.Peek().Directories[torename].FullName; selectedMode = 1; } else { name = history.Peek().Files[torename - history.Peek().Directories.Length].Name; fullname = history.Peek().Files[torename - history.Peek().Directories.Length].FullName; selectedMode = 2; } string path = fullname.Remove(fullname.Length - name.Length); Console.WriteLine("Please enter the new name with extension"); string newname = Console.ReadLine(); if (selectedMode == 1) { new DirectoryInfo(history.Peek().Directories[torename].FullName).MoveTo(path + newname); } else { new FileInfo(history.Peek().Files[torename - history.Peek().Directories.Length].FullName).MoveTo(path + newname); } history.Pop(); if (history.Count == 0) { Layer lay = new Layer { Directories = firstdir.GetDirectories(), Files = firstdir.GetFiles(), SelectedIndex = i }; history.Push(lay); } else { torename = history.Peek().SelectedIndex; DirectoryInfo dir = history.Peek().Directories[torename]; Layer ly = new Layer { Directories = dir.GetDirectories(), Files = dir.GetFiles(), SelectedIndex = i }; history.Push(ly); } } else if (key.Key == ConsoleKey.Escape) { quit = true; } } }