Currently I have a program that searches a user set directory and sub-directories for music files and adds them to a collection. However if one of the directories it comes accross is protected then the program falls over. I wanted to know how I can check if the user has access to the directory before trying to search it to avoid this problem. Below is the code I'm using for the search, it currently contains a basic work around for "System Volume Information" but as there is a possibility that there may be other protected directories I wanted to change this to include them.

    public void SearchForMusic()
    {
        //Searches selected directory and its sub directories for music files and adds their path to ObservableCollection<string> MusicFound
        foreach (string ext in extentions)
        {
            foreach (string song in Directory.GetFiles(SearchDirectory, ext))
            {
                musicFound.Add(song);                   
            }

            foreach (string directory in Directory.GetDirectories(SearchDirectory))
            {
                if (directory.Contains("System Volume Information"))
                {

                }
                else
                {
                    foreach (string song in Directory.GetFiles(directory, ext))
                    {
                    musicFound.Add(song);
                    }

                    foreach (string subDirectory in Directory.GetDirectories(directory))
                    {
                        foreach (string subSong in Directory.GetFiles(subDirectory, ext))
                        {
                            musicFound.Add(subSong);
                        }
                    }
                }
            }
        }
    }

Many thanks :)

有帮助吗?

解决方案

By far the easiest way to be sure that you have access to a file system object is to attempt to access it. If it fails with an Access Denied error, then you don't have access. Just detect that error condition and proceed with the next item in the search.

In other words, delegate checking access to the system which is, after all, the ultimate arbiter of access rights.

其他提示

You can check this question by replacing the Write with Read permissions. Also, wrap your code in a try catch block and if the exception is thrown, you can assume (or properly check the exception type to be sure) that the directory cannot be traversed.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top