C# 找不到 Directory.GetDirectories 路径的一部分

C# Could not find a part of the path with Directory.GetDirectories

我正在尝试制作一个应用程序,将卷复制到计算机中的选定位置。 该卷是一个外部硬盘,其中包含我以前计算机 C 卷的副本。

首先,当我尝试复制目录和文件时,我创建了一个递归函数来获取目录和文件并将它们复制到新位置,递归函数获取目录 Directory.GetDirectories 函数,在我得到子目录后,我使用相同的函数来获取子目录的子目录并一直这样做直到没有目录可获取,一切正常但是当我尝试在我的卷上使用该应用程序时我"Application Data" 文件夹出现无限循环,这意味着 GetDirectories 函数一次又一次地在前一个 "Application Data" 中找到 "Application Data" 文件夹。 为了解决这个问题,我检查了路径是否不包含 "Application Data\Application Data" 并且只是我使用了 GetDirectories 函数。 也许那个解决方案导致了我要问的问题。

问题是当我使用函数 GetDirectories 时出现异常:"Could not find a part of the path" 但我的代码如下所示:

if(Directory.Exist(path))
{
    string[] subdirs = Directory.GetDirectories(path);
}

那么为什么Exist函数找到了文件夹,而GetDirectories函数却找不到呢? 顺便说一句,该应用程序可以在不属于 windows 系统的目录上正常运行。 那么问题是什么?我该如何解决或如何制作复制 C 卷的复制应用程序? 非常感谢

来自Microsoft support

A service that runs under a LocalSystem account or under a local user account can only access mapped drives that the service creates. Mapped drives are stored for each logon session. If a service runs under a LocalSystem account or under a local user account that does not create certain mapped drives, the service cannot access these mapped drives. Additionally, a service that runs under a local user account that creates certain mapped drives also receives a new set of mapped drives if you log off and then you log on again as the same local user.

有一个解决方法,但不是必需的,只需对这些库使用 try-catch:

if(Directory.Exist(path))
{
    try
    {
        string[] subdirs = Directory.GetDirectories(path);
    }
    catch (Exception ex)
    {

    }
}

或者,或者,使用 Directory.GetDirectories SearchOptions 这样您就可以排除某些子目录。