Is asynchronous which means the UI remains responsive.

MiPakTeh 1,476 Reputation points
2021-02-21T05:01:23.34+00:00

I test for read All files in C:\ .I try this code. but nothing happen.
somebody show me why.

In Form code is;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using Learning_8;

namespace Learning_8  
{  
    public partial class Form1 : Form  
    {  
  
        private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();  
  
        public Form1()  
        {  
            InitializeComponent();  
  
            Operations.OnTraverseEvent += OperationsOnOnTraverseEvent;  
        }  
  
        private void OperationsOnOnTraverseEvent(string status)  
        {  
            if(ResultsLabel.InvokeRequired)  
                {  
                ResultsLabel.Invoke((MethodInvoker)(() =>  
                ResultsLabel.Text = status));  
                ResultsLabel.Refresh();  
            };  
        }  
  
        private async void Button1_Click(object sender, EventArgs e)  
        {  
            if (_cancellationTokenSource.IsCancellationRequested)  
            {  
                _cancellationTokenSource.Dispose();  
                _cancellationTokenSource = new CancellationTokenSource();  
            }  
  
            var directoryInfo = new DirectoryInfo("D:\\");  
  
            try  
            {  
                await Operations.RecursiveFolders(  
                    directoryInfo,  
                    new[] { "*.txt" },  
                    _cancellationTokenSource.Token);  
  
                if (Operations.Cancelled)  
                {  
                    MessageBox.Show(@"You cancelled the operation");  
                }  
                else  
                {  
                    MessageBox.Show(@"Done");  
                }  
            }  
            catch (Exception ex)  
            {  
                MessageBox.Show(ex.Message);  
            }  
        }  
  
        private void Button2_Click(object sender, EventArgs e)  
        {  
            _cancellationTokenSource.Cancel();  
        }  
    }  
}  
  1. Class File is; using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Xml.Linq;
    using System.IO;
    using System.Threading; namespace Learning_8
    {
    public class Operations
    {
    public delegate void OnException(Exception exception);
    public static event OnException OnExceptionEvent;
    public delegate void OnUnauthorizedAccessException(string message);
    public static event OnUnauthorizedAccessException UnauthorizedAccessExceptionEvent;
    public delegate void OnTraverseFolder(string status);
    public static event OnTraverseFolder OnTraverseEvent;
    public delegate void OnTraverseExcludeFolder(string sender);
    public static event OnTraverseExcludeFolder OnTraverseExcludeFolderEvent;
    public static bool Cancelled = false;
        public static async Task RecursiveFolders(DirectoryInfo directoryInfo, string[] excludeFileExtensions, CancellationToken ct)  
        {  
    
            if (!directoryInfo.Exists)  
            {  
                if (OnTraverseEvent != null)  
                    OnTraverseEvent("Nothing to process");  
                return;  
            }  
    
            if (!excludeFileExtensions.Any(directoryInfo.FullName.Contains))  
            {  
                await Task.Delay(1);  
                if (OnTraverseEvent != null)  
                    OnTraverseEvent(directoryInfo.FullName);  
    
            }  
            else  
            {  
                if (OnTraverseExcludeFolderEvent != null)  
                    OnTraverseExcludeFolderEvent(directoryInfo.FullName);  
            }  
    
            DirectoryInfo folder = null;  
    
            try  
            {  
                await Task.Run(async () =>  
                {  
                    foreach (DirectoryInfo dir in directoryInfo.EnumerateDirectories())  
                    {  
    
                        folder = dir;  
    
                        if ((folder.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden || (folder.Attributes & FileAttributes.System) == FileAttributes.System || (folder.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)  
                        {  
    
                            if (OnTraverseExcludeFolderEvent != null)  
                                OnTraverseExcludeFolderEvent($"* {folder.FullName}");  
    
                            continue;  
    
                        }  
    
                        if (!Cancelled)  
                        {  
    
                            await Task.Delay(1);  
                            await RecursiveFolders(folder, excludeFileExtensions, ct);  
    
                        }  
                        else  
                        {  
                            return;  
                        }  
    
                        if (ct.IsCancellationRequested)  
                        {  
                            ct.ThrowIfCancellationRequested();  
                        }  
    
                    }  
                });  
    
            }  
            catch (Exception ex)  
            {  
                if (ex is OperationCanceledException)  
                {  
                    Cancelled = true;  
                }  
                else if (ex is UnauthorizedAccessException)  
                {  
    
                    if (UnauthorizedAccessExceptionEvent != null)  
                        UnauthorizedAccessExceptionEvent($"Access denied '{ex.Message}'");  
    
                }  
                else  
                {  
    
                    if (OnExceptionEvent != null)  
                        OnExceptionEvent(ex);  
    
                }  
            }  
        }  
    
        public static void RecursiveFolders(string path, int indentLevel)  
        {  
    
            try  
            {  
    
                if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)  
                {  
    
                    foreach (string folder in Directory.GetDirectories(path))  
                    {  
                        Debug.WriteLine($"{new string(' ', indentLevel)}{System.IO.Path.GetFileName(folder)}");  
                        RecursiveFolders(folder, indentLevel + 2);  
                    }  
    
                }  
    
            }  
            catch (UnauthorizedAccessException unauthorized)  
            {  
                Debug.WriteLine($"{unauthorized.Message}");  
            }  
        }  
    
    }  
    
    }

Thank.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,299 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.5K Reputation points
    2021-02-21T09:29:14.617+00:00

    Try another handler:

    private void OperationsOnOnTraverseEvent( string status )
    {
       ResultsLabel.Invoke( (MethodInvoker)( ( ) => ResultsLabel.Text = status ) );
    }
    

  2. Karen Payne MVP 35,196 Reputation points
    2021-02-21T11:30:14.187+00:00

    Hello,

    Download the following code sample which is setup to work from the root of C drive.

    70358-11111111111.png