我需要从 C# windows 服务中获取用户目录...
...比如 C:\Users\myusername\
理想情况下,我希望有漫游路径......
...就像 C:\Users\myusername\AppData\Roaming\
当我在控制台程序中使用以下内容时,我得到了正确的用户目录......
System.Environment.GetEnvironmentVariable("USERPROFILE");
...但是当我在服务中使用相同的变量时,我得到...
C:\WINDOWS\system32\config\systemprofile
如何从服务获取用户文件夹甚至漫游文件夹位置?
提前致谢。
我搜索过从 Windows 服务获取用户的配置文件路径。我发现了这个问题,它不包括实现它的方法。当我找到解决方案时,部分基于 Xavier J 对他的答案的评论,我决定将其发布在这里供其他人使用。
以下是执行此操作的一段代码。我已经在几个系统上对其进行了测试,它应该可以在从 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)