Exercise
Surf Directory
Objetive
Create a program that displays the files in the current folder and allows the user to move up and down the list. If the user presses Enter on a folder name, they will enter that folder. If they press Enter on a file, the file will be opened.
Example Code
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
using System.Collections;
class SurfDirectory
{
static int position = 0;
static List items;
static string directory = ".";
static void Main()
{
while (true)
{
Console.Clear();
items = GetItems(directory);
ShowItems();
ShowIndications();
ReadKeys();
Thread.Sleep(200);
}
}
static void OpenFile(Item item)
{
if (item.IsFile)
{
Process.Start(item.Name);
}
}
static void ReadKeys()
{
ConsoleKeyInfo key = Console.ReadKey();
switch (key.Key)
{
case ConsoleKey.UpArrow:
if (position > 0)
{
position--;
}
break;
case ConsoleKey.DownArrow:
if (position < items.Count - 1)
{
position++;
}
break;
case ConsoleKey.Enter:
Item item = items[position];
if (item.IsFile)
{
OpenFile(item);
}
else
{
directory = item.Path;
}
break;
}
}
static void ShowSelected(int i)
{
if (i == position)
{
Console.SetCursorPosition(0, position);
Console.BackgroundColor = ConsoleColor.DarkCyan;
}
else
{
Console.BackgroundColor = ConsoleColor.Black;
}
}
static List GetItems(string direc)
{
try
{
List items = new List();
string[] directories = Directory.GetDirectories(direc);
foreach (string directory in directories)
{
items.Add(new Item(directory, false));
}
string[] files = Directory.GetFiles(direc);
foreach (string file in files)
{
items.Add(new Item(file, true));
}
return items;
}
catch
{
Console.WriteLine("Error reading items.");
return null;
}
}
static void ShowItems()
{
int i = 0;
foreach (Item item in items)
{
ShowSelected(i);
Console.WriteLine(item.Path);
i++;
}
Console.BackgroundColor = ConsoleColor.Black;
}
static void ShowIndications()
{
Console.SetCursorPosition(0, 23);
Console.WriteLine("Press arrow up for move up | Press arrow down for move down");
}
}
public class Item
{
public string Path { get; set; }
public bool IsFile { get; set; }
public string Name
{
get { return Path.Substring(2); }
}
public Item(string path, bool isFile)
{
this.Path = path;
this.IsFile = isFile;
}
}