【问题标题】:Get SpecialFolder.MyDocuments folders of each user获取每个用户的 SpecialFolder.MyDocuments 文件夹
【发布时间】:2017-07-06 09:47:34
【问题描述】:

我的机器上正在运行一个 Windows 服务。如何获取每个用户的 MyDocuments 文件夹?

例如:

对于 Windows XP,我必须获取列表:

  • C:\Documents and Settings\User1\我的文档
  • C:\Documents and Settings\User2\My Documents
  • ...

对于 Windows 10,我必须获取列表:

  • C:\Users\User1\Documents\

  • C:\Users\User2\Documents\

  • ...

如何获得这些列表?

【问题讨论】:

    标签: c# .net windows service


    【解决方案1】:

    我建议使用this solution,然后只枚举文件夹(针对每个用户)。

    // 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
            }
        }
    }
    

    【讨论】:

    • 这不是一个好主意,您不能硬编码“文档”字符串。也可以将这些特殊文件夹移到配置文件目录之外。
    • 理论上,是的,你是对的。稍后我将编辑此答案以获取文档文件夹的实际名称。
    • 文档文件夹可以有每个用户的自定义名称,没有真正的通用名称。
    • 如你所说可以拥有。在新机器上,它们都将位于 %userpofile% 目录中,名称为“documents”或“mydocuments”。问题未指定您所描述的行为。
    • 我将文件夹从 C:\Users\Admin\Documents\ 移动到 D:\Abracadabra,但我无法从 Windows 服务获取 "D:\Abracadabra" :-(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多