Get SpecialFolder.MyDocuments folders of each user

2019-08-07 18:24发布

问题:

I have a windows service running on my machine. How can I get MyDocuments folders of each users?

For example:

For Windows XP I must get list:

  • C:\Documents and Settings\User1\My Documents
  • C:\Documents and Settings\User2\My Documents
  • ...

For Windows 10 I must get list:

  • C:\Users\User1\Documents\

  • C:\Users\User2\Documents\

  • ...

How can I get these lists ?

回答1:

I would suggest using this solution and then just enumerate folders ( for each user ).

// getUserProfilesPath() is a method from https://stackoverflow.com/a/41752173/3179310
string path = getUserProfilesPath();
// now use WMIC to get all users on the local machine
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject result in searcher.Get())
{
    // and check if their folder exists
    if(Directory.Exists(Path.Combine(path, result["Name"])))
    {
        // user folder exists so now check if it has Documents folder
        if(DirectoryExists(Path.Combine(path, result["Name"], "Documents")))
        {
            DirectoryInfo userDocuments = new DirectoryInfo(Path.Combine(path, result["Name"], "Documents"));
            // userDocuments is now a directory info of that user's documents folder
        }
    }
}