Certainly! Below is an example C# script that checks a specified directory for subfolders and populates a ListBox with the names of those folders.
You will need to have a Windows Forms Application set up with a ListBox control in your form. The control must be named listBoxFolders. The script includes a method called PopulateList that performs the folder check and populates the list.
Here's the complete code for the form:
using System;
using System.IO;
using System.Windows.Forms;
namespace FolderChecker
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
PopulateList(@"C:\YourDirectoryPath"); // Change this to your target directory
}
private void PopulateList(string directoryPath)
{
// Clear the existing items in the ListBox
listBoxFolders.Items.Clear();
// Check if the directory exists
if (Directory.Exists(directoryPath))
{
// Get the subdirectories
string[] subdirectories = Directory.GetDirectories(directoryPath);
// Add each subdirectory to the ListBox
foreach (string subdirectory in subdirectories)
{
// Just add the folder name, not the full path
listBoxFolders.Items.Add(Path.GetFileName(subdirectory));
}
}
else
{
MessageBox.Show("The specified directory does not exist.",
"Directory Not Found",
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
}
}
}
Instructions to Use:
-
Create a Windows Forms Application: Start by creating a new Windows Forms Application project in Visual Studio.
-
Add a ListBox Control:
- Drag and drop a
ListBox control onto your form from the toolbox.
- Set the
Name property of the ListBox to listBoxFolders.
-
Modify Directory Path: In the PopulateList method call in the constructor, replace @"C:\YourDirectoryPath" with the actual path you want to check for folders.
-
Run the Application: You can now run the application, and it will populate the ListBox with the folder names from the specified directory.
Note:
- Ensure that the application has the necessary permissions to access the specified directory.
- You can implement additional functionality, such as refreshing the ListBox on button click or handling exceptions as needed.