Ads

C# Programming 25 - Display all the files and Folder Names inside Folder

Hello All,

In this article we will learn how to display all the files and folder names inside folder.

To display all the file and folder names inside a folder in C#, you can use the Directory class and its GetFiles and GetDirectories methods. Here's an example:


Example:


using System;
using System.IO;

public class Program
{
    public static void Main(string[] args)
    {
        string folderPath = @"C:\Path\To\Folder";

        // Display file names
        string[] files = Directory.GetFiles(folderPath);
        Console.WriteLine("Files:");
        foreach (string file in files)
        {
            string fileName = Path.GetFileName(file);
            Console.WriteLine(fileName);
        }

        Console.WriteLine();

        // Display folder names
        string[] folders = Directory.GetDirectories(folderPath);
        Console.WriteLine("Folders:");
        foreach (string folder in folders)
        {
            string folderName = Path.GetFileName(folder);
            Console.WriteLine(folderName);
        }
    }
}

Replace "C:\Path\To\Folder" with the path of the folder you want to display the file and folder names for.

In the Main method, the code first retrieves an array of file paths using Directory.GetFiles(folderPath). It then iterates over the files and uses Path.GetFileName to extract just the file name (without the full path) and displays it.

Next, the code retrieves an array of folder paths using Directory.GetDirectories(folderPath). It iterates over the folders, extracts the folder name using Path.GetFileName, and displays it.

The output will be the list of file names followed by the list of folder names present inside the specified folder.

Thats it for this article, see you in next article.

Until then take care bye.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !