I'm using C# for a project and thought I would get a feel for the language by making some simple programs. My current program is a simple file recurser that prints the names of files and directories. Any suggestions would be greatly appreciated.
using System;
using System.IO;
namespace FileRecurser
{
class Program
{
private static int indent = -2; // Start off at -2 so first indent
// starts at 0.
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: recurser <directory>");
return;
}
// Check if directory exists.
string directory = args[0];
if (!Directory.Exists(directory))
{
Console.WriteLine("Error: {0} doesn't exist!", directory);
return;
}
Console.WriteLine("Printing files for {0}\n", directory);
PrintDirectoryFiles(directory);
}
private static void PrintDirectoryFiles(string directory)
{
indent += 2;
// If any subdirectories.
string[] subdirectories = Directory.GetDirectories(directory);
if (subdirectories.Length != 0)
{
foreach (var subdirectory in subdirectories)
{
// Change color to reflect directory.
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(
"{0}{1}:",
new String(' ', indent),
Path.GetFileName(subdirectory)
);
Console.ResetColor();
PrintDirectoryFiles(subdirectory);
Console.WriteLine();
}
}
// Print file names.
string[] files = Directory.GetFiles(directory);
if (files.Length != 0)
{
foreach (var file in files)
{
Console.WriteLine(
"{0}{1}",
new String(' ', indent),
Path.GetFileName(file)
);
}
}
indent -= 2;
}
}
}