2

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 ?

Kirill
  • 429
  • 1
  • 6
  • 18

1 Answers1

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
        }
    }
}
mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
  • This is not a good idea, you cannot hardcode the "Documents" string. It is also possible to move these special folders outside the profile directory. – Anders Jul 06 '17 at 12:12
  • Theoretically, yes, you're right. I will edit this answer later on to get the actual name of the documents folder. – mrogal.ski Jul 06 '17 at 12:27
  • The documents folder can have per-user custom names, there is no true generic name. – Anders Jul 06 '17 at 12:30
  • As you said **CAN HAVE**. On fresh machine they will all be in %userpofile% directory with the name "documents" or "mydocuments". Question did not specified behavior that you're describing. – mrogal.ski Jul 06 '17 at 12:36
  • I moved folder from C:\Users\Admin\Documents\ to D:\Abracadabra, but I can't get "D:\Abracadabra" from Windows Service :-( – Kirill Jul 06 '17 at 12:41
  • So why did you move it then? If you want to track all of these things it's almost impossible to get the correct path. – mrogal.ski Jul 06 '17 at 12:42
  • User moved his Documents folder (I don't know why). And Windows Service should detect this. So it's impossible. Thanks for the answeres – Kirill Jul 06 '17 at 12:47
  • It is still possible but I doubt that somebody will give you solution like that, you have more chances to get a solid answer if you show some effort on that topic. – mrogal.ski Jul 06 '17 at 12:49