Windows窗体ArgumentException未处理

时间:2014-05-20 17:37:55

标签: c#

我有一个图像幻灯片项目,用户需要选择一个图像文件夹,表单在PictureBox和幻灯片中显示,项目运行并允许我选择一个图像文件夹,之后它会抛出一个ArgumentException意味着如果目录不存在则抛出。下面是抛出异常的方法的代码:

public static string[] GetFiles(string path, string searchPattern)
    {
        string[] patterns = searchPattern.Split(';');
        List<string> files = new List<string>();
        foreach (string filter in patterns)
        {
            // Iterate through the directory tree and ignore the 
            // DirectoryNotFoundException or UnauthorizedAccessException 
            // exceptions.                 

            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!Directory.Exists(path))
            {
                throw new ArgumentException();
            }
            dirs.Push(path);

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown 
                // if we do not have discovery permission on a folder or 
                // file. It may or may not be acceptable to ignore the 
                // exception and continue enumerating the remaining files 
                // and folders. It is also possible (but unlikely) that a 
                // DirectoryNotFound exception will be raised. This will 
                // happen if currentDir has been deleted by another 
                // application or thread after our call to Directory.Exists. 
                // The choice of which exceptions to catch depends entirely 
                // on the specific task you are intending to perform and 
                // also on how much you know with certainty about the 
                // systems on which this code will run.
                catch (UnauthorizedAccessException)
                {
                    continue;
                }
                catch (DirectoryNotFoundException)
                {
                    continue;
                }

                try
                {
                    files.AddRange(Directory.GetFiles(currentDir, filter));
                }
                catch (UnauthorizedAccessException)
                {
                    continue;
                }
                catch (DirectoryNotFoundException)
                {
                    continue;
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                {
                    dirs.Push(str);
                }
            }
        }

        return files.ToArray();
    }

将非常感谢协助。

0 个答案:

没有答案