gpt4 book ai didi

c#服务: how to get user profile folder path

转载 作者:行者123 更新时间:2023-12-04 11:46:15 25 4
gpt4 key购买 nike

我需要从 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;
}
}

关于c#服务: how to get user profile folder path,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38252474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com