Xi *_*Vix 6 c# profile windows-services path
我需要从 C# windows 服务中获取用户目录...
...像 C:\Users\myusername\
理想情况下,我想要漫游路径...
...像 C:\Users\ myusername\AppData\Roaming\
当我在控制台程序中使用以下内容时,我得到了正确的用户目录...
System.Environment.GetEnvironmentVariable("USERPROFILE");
Run Code Online (Sandbox Code Playgroud)
...但是当我在服务中使用相同的变量时,我得到...
C:\WINDOWS\system32\config\systemprofile
如何从服务中获取用户文件夹甚至漫游文件夹位置?
提前致谢。
小智 6
我搜索过从 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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
首先,您需要使用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
服务不会像用户一样登录,除非该服务配置为使用特定用户的配置文件。所以它不会指向“用户”文件夹。
| 归档时间: |
|
| 查看次数: |
8078 次 |
| 最近记录: |