list files in csharp

// tags: csharp, file, io, list, directory

using System; using System.IO;

class Program { static void Main(string[] args) { string path = @"C:\Users\user\Documents"; // specify the directory path that you want to list files from string[] files = Directory.GetFiles(path); // get all files in the directory specified by the path

main.cs
    // loop through each file in the array and print out the file name
    Console.WriteLine("Files in {0}:\n", path);
    foreach (string file in files) {
        Console.WriteLine(Path.GetFileName(file));
    }
}
215 chars
7 lines

}

main.cs

This C# code uses the `System.IO` namespace to list all files in a specified directory. The `GetFiles` method is used to retrieve an array of strings representing the full path of each file in the directory. We then loop through each file and print its name using the `GetFileName` method from the `Path` class.
313 chars
3 lines

related categories

gistlibby LogSnag