简体   繁体   English

继续Foreach循环出错

[英]Continue Foreach Loop On Error

I want to continue my code when error comes up , but i dont know how ... 错误出现时我想继续执行我的代码,但是我不知道如何...

here's my code : 这是我的代码:

foreach(string path in Directory.GetDirectories(@"C:\", "*.*", SearchOption.AllDirectories)
{
    Console.WriteLine(path);
}

And the error comes on foreach(string path in Directory.GetDirectories(@"C:\\", "*.*", SearchOption.AllDirectories) and i don't know how to continue this loop 错误出现在foreach(string path in Directory.GetDirectories(@"C:\\", "*.*", SearchOption.AllDirectories) ,我不知道如何继续此循环

and the error : 和错误:

Unauthorized access 越权存取

And even i run my code as Administrator this error comes up again 甚至我以管理员身份运行我的代码,此错误再次出现

Thanks, 谢谢,

The best is to use recursive search and not using SearchOption.AllDirectories , but rather SearchOption.TopDirectoryOnly 最好是使用递归搜索,而不要使用SearchOption.AllDirectories ,而是要使用SearchOption.TopDirectoryOnly

If you use SearchOption.AllDirectories , one access violation will break your entire loop even before any file/directory is processed. 如果使用SearchOption.AllDirectories ,则即使在处理任何文件/目录之前, 一次访问冲突都将破坏您的整个循环。 But if you use SearchOption.TopDirectoryOnly , you only skip what is inaccessible. 但是,如果您使用SearchOption.TopDirectoryOnly ,则只会跳过无法访问的内容。

Thus, to do it, you can create a method which receives a directory path as input. 因此,要做到这一点,您可以创建一个方法来接收目录路径作为输入。 And in that method, if the input directory have child directory(ies) (see Directory.GetDirectories(string path) method, you call the method again for each child directory (recursive call) before you process all the files in the directory. Else, get the files (see Directory.GetFiles ) in the directory and process them immediately. 并且在该方法中,如果输入目录具有子目录(请参见Directory.GetDirectories(string path)方法),则在处理目录中的所有文件之前,请为每个子目录再次调用该方法(递归调用)。 ,获取Directory.GetFiles的文件(请参阅Directory.GetFiles )并立即对其进行处理。

Then for the method above, one way is to prevent the code crash when you cannot access certain file/directory is by using try-catch block for each child directory reading and file reading. 然后,对于上述方法,一种方法是在无法访问某些文件/目录时防止代码崩溃,方法是为每个子目录读取和文件读取使用try-catch块。 This way, if one file/folder cannot be accessed, your code will still be running, finding the processing the next file/directory. 这样,如果无法访问一个文件/文件夹,您的代码仍将运行,查找下一个文件/目录的处理。

Alternatively, you can use Directory.GetAccessControl() per child directory check to see if you have an access to a Directory before hand (this option is rather hard though). 另外,您可以对每个子目录使用Directory.GetAccessControl()检查您是否可以事先访问Directory (尽管此选项很难)。

Edit (code added): 编辑(添加代码):

Something like this will do: 这样的事情会做:

public static List<string> GetAllAccessibleDirectories(string path, string searchPattern) {
    List<string> dirPathList = new List<string>();
    try {
        List<string> childDirPathList = Directory.GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly).ToList(); //use TopDirectoryOnly
        if (childDirPathList == null || childDirPathList.Count <= 0) //this directory has no child
            return null;
        foreach (string childDirPath in childDirPathList) { //foreach child directory, do recursive search
            dirPathList.Add(childDirPath); //add the path
            List<string> grandChildDirPath = GetAllAccessibleDirectories(childDirPath, searchPattern);
            if (grandChildDirPath != null && grandChildDirPath.Count > 0) //this child directory has children and nothing has gone wrong
                dirPathList.AddRange(grandChildDirPath.ToArray()); //add the grandchildren to the list
        }
        return dirPathList; //return the whole list found at this level
    } catch {
        return null; //something has gone wrong, return null
    }
}

And to call it, you can do something like this 可以这样称呼它

string rootpath = @"C:\DummyRootFolder";
List<string> dirList = GetAllAccessibleDirectories(rootpath, "*.*"); //you get all accessible directories here

In the dirList you will get all the directories that you search for, and if there is access violation along the way, it will only affects sub-directories search due to the try-catch block. dirList您将获得要搜索的所有目录,并且如果途中发生访问冲突,由于try-catch块,它只会影响子目录搜索。

Note that the rootpath is excluded in the method. 请注意,该方法中不包括根rootpath But if you want to add it to the list too, you could simply do 但是,如果您也想将其添加到列表中,则只需

dirList.Insert(0, path); //do this after you get dirList

There are also more complicated ways of doing this by using Directory.GetAccessControl and PermissionSet 还有更复杂 的方式 做的 ,通过使用该Directory.GetAccessControlPermissionSet

Hope it may clarify. 希望它可以澄清。

According to the documentation, you should look at EnumerateDirectories for performance reasons: 根据文档,出于性能原因,您应该查看EnumerateDirectories:

https://msdn.microsoft.com/en-us/library/c1sez4sc(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/c1sez4sc(v=vs.110).aspx

Also, it appears that this question has already been answered before: 另外,似乎这个问题之前已经被回答过:

Directory.EnumerateFiles => UnauthorizedAccessException Directory.EnumerateFiles => UnauthorizedAccessException

Hope this helps! 希望这可以帮助!

How about this: 这个怎么样:

foreach (string path in Directory.GetDirectories(@"C:\", "*.*", SearchOption.AllDirectories)) {

            try { 
                Console.WriteLine(path);
            } catch (Exception ex) {
                Console.WriteLine("Unable to access directories in path: " + path);
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM