c#服务:如何获取用户配置文件文件夹路径

c# service: how to get user profile folder path

我需要从 C# windows 服务中获取用户目录...
...像 C:\Users\myusername\
理想情况下,我希望有漫游路径...
...像 C:\Users\myusername\AppData\Roaming\
当我在控制台程序中使用以下内容时,我得到了正确的用户目录...

System.Environment.GetEnvironmentVariable("USERPROFILE"); 

...但是当我在服务中使用相同的变量时,我得到...
C:\WINDOWS\system32\config\systemprofile
我如何从服务中获取用户文件夹甚至漫游文件夹位置?
提前致谢。

服务不会像用户一样登录,除非服务被配置为使用特定用户的配置文件。所以它不会指向 "user" 个文件夹。

首先,您需要使用 Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

Environment.SpecialFolder.ApplicationData 用于漫游配置文件。

在此处查找所有 SpecialFolder 枚举值:https://msdn.microsoft.com/en-us/library/system.environment.specialfolder(v=vs.110).aspx

正如其他人所指出的,该服务将 运行 在帐户 LocalSystem/LocalService/NetworkService 下,具体取决于配置:https://msdn.microsoft.com/en-us/library/windows/desktop/ms686005(v=vs.85).aspx

我搜索了从 Windows 服务获取用户的配置文件路径。我发现了这个问题,其中不包括一种方法。由于我找到了解决方案,部分基于 Xavier J 对他的回答的评论,我决定 post 在这里为其他人提供。

以下是执行该操作的一段代码。我已经在几个系统上对其进行了测试,它应该可以在从 Windows XP 到 Windows 10 1903.

的不同操作系统上运行

    //You can either provide User name or SID
    public string GetUserProfilePath(string userName, string userSID = null)
    {
        try
        {
            if (userSID == null)
            {
                userSID = GetUserSID(userName);
            }

            var keyPath = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" + userSID;

            var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(keyPath);
            if (key == null)
            {
                //handle error
                return null;
            }

            var profilePath = key.GetValue("ProfileImagePath") as string;

            return profilePath;
        }
        catch
        {
            //handle exception
            return null;
        }
    }

    public string GetUserSID(string userName)
    {
        try
        {
            NTAccount f = new NTAccount(userName);
            SecurityIdentifier s = (SecurityIdentifier)f.Translate(typeof(SecurityIdentifier));
            return s.ToString();
        }
        catch
        {
            return null;
        }
    }