Ejercicio
Navegar por el directorio
Objetivo
Cree un programa para mostrar los archivos en el directorio actual y para permitir que el usuario se mueva hacia arriba y hacia abajo en esa lista. Si el usuario presiona Intro en un nombre de directorio, ingresará ese directorio; si presiona Intro en un archivo, ese archivo se iniciará.
Código
Imports System
Imports System.IO
Imports System.Threading
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Collections
Class SurfDirectory
Shared position As Integer = 0
Shared items As List
Shared directory As String = "."
Private Shared Sub Main()
While True
Console.Clear()
items = GetItems(directory)
ShowItems()
ShowIndications()
ReadKeys()
Thread.Sleep(200)
End While
End Sub
Private Shared Sub OpenFile(ByVal item As Item)
If item.IsFile Then
Process.Start(item.Name)
End If
End Sub
Private Shared Sub ReadKeys()
Dim key As ConsoleKeyInfo = Console.ReadKey()
Select Case key.Key
Case ConsoleKey.UpArrow
If position > 0 Then
position -= 1
End If
Case ConsoleKey.DownArrow
If position < items.Count - 1 Then
position += 1
End If
Case ConsoleKey.Enter
Dim item As Item = items(position)
If item.IsFile Then
OpenFile(item)
Else
directory = item.Path
End If
End Select
End Sub
Private Shared Sub ShowSelected(ByVal i As Integer)
If i = position Then
Console.SetCursorPosition(0, position)
Console.BackgroundColor = ConsoleColor.DarkCyan
Else
Console.BackgroundColor = ConsoleColor.Black
End If
End Sub
Private Shared Function GetItems(ByVal direc As String) As List
Try
Dim items As List = New List()
Dim directories As String() = Directory.GetDirectories(direc)
For Each directory As String In directories
items.Add(New Item(directory, False))
Next
Dim files As String() = Directory.GetFiles(direc)
For Each file As String In files
items.Add(New Item(file, True))
Next
Return items
Catch
Console.WriteLine("Error reading items.")
Return Nothing
End Try
End Function
Private Shared Sub ShowItems()
Dim i As Integer = 0
For Each item As Item In items
ShowSelected(i)
Console.WriteLine(item.Path)
i += 1
Next
Console.BackgroundColor = ConsoleColor.Black
End Sub
Private Shared Sub ShowIndications()
Console.SetCursorPosition(0, 23)
Console.WriteLine("Press arrow up for move up | Press arrow down for move down")
End Sub
End Class
Public Class Item
Public Property Path As String
Public Property IsFile As Boolean
Public ReadOnly Property Name As String
Get
Return Path.Substring(2)
End Get
End Property
Public Sub New(ByVal path As String, ByVal isFile As Boolean)
Me.Path = path
Me.IsFile = isFile
End Sub
End Class