Hi @MIPAKTEH_1 , Welcome to Microsoft Q&A,
You need to adjust your logic to ensure that you get the path to the file or directory from the FileSystemWatcher and pass it as a parameter to the getFiles method.
This is a one-time effect that occurs when you create a new file in the target folder.
void OnCreated_(object sender, FileSystemEventArgs e)
{
try
{
// e.FullPath is the full path of the created file or directory
string createdPath = e.FullPath;
if (Directory.Exists(createdPath))
{
// If it is a directory
getFiles(createdPath);
}
else if (File.Exists(createdPath))
{
// If it is a file, get the directory
string directory = Path.GetDirectoryName(createdPath);
getFiles(directory);
}
}
catch (Exception exception)
{
Debug.WriteLine($"Error: {exception.Message}");
}
}
// Recursively traverse the directory and update the ListBox
void getFiles(string directory)
{
try
{
// Get files and subdirectories in the directory
string[] files = Directory.GetFiles(directory);
string[] directories = Directory.GetDirectories(directory);
// Process files
foreach (string file in files)
{
listBox1.Invoke((Action)(() => listBox1.Items.Add(file))); // Update ListBox
}
// Process subdirectories
foreach (string subDirectory in directories)
{
listBox2.Invoke((Action)(() => listBox2.Items.Add(subDirectory))); // Update ListBox
getFiles(subDirectory); // Recursive call
}
}
catch (UnauthorizedAccessException)
{
Debug.WriteLine($"Access denied to: {directory}");
}
catch (Exception ex)
{
Debug.WriteLine($"Error processing directory: {directory}, {ex.Message}");
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.