How to recursively list all the files in a directory in C#?

前端 未结 22 2549
长发绾君心
长发绾君心 2020-11-22 00:07

How to recursively list all the files in a directory and child directories in C#?

22条回答
  •  故里飘歌
    2020-11-22 00:56

    Some excellent answers but these answers did not solve my issue.

    As soon as a folder permission issue arises: "Permission Denied" the code fails. This is what I used to get around the "Permission Denied" issue:

    private int counter = 0;
    
        private string[] MyDirectories = Directory.GetDirectories("C:\\");
    
        private void ScanButton_Click(object sender, EventArgs e)
        {
            Thread MonitorSpeech = new Thread(() => ScanFiles());
            MonitorSpeech.Start();
        }
    
        private void ScanFiles()
        {
            string CurrentDirectory = string.Empty;
    
            while (counter < MyDirectories.Length)
            {
                try
                {
                    GetDirectories();
                    CurrentDirectory = MyDirectories[counter++];
                }
                catch
                {
                    if (!this.IsDisposed)
                    {
                        listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + CurrentDirectory); });
                    }
                }
            }
        }
    
        private void GetDirectories()
        {
            foreach (string directory in MyDirectories)
            {
                GetFiles(directory);
            }
        }
    
        private void GetFiles(string directory)
        {
            try
            {
                foreach (string file in Directory.GetFiles(directory, "*"))
                {
                    listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(file); });
                }
            }
            catch
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + directory); });
            }
        }
    

    Hope this helps others.

提交回复
热议问题