我需要从C#windows服务中获取用户目录...
...比如C:\ Users \ myusername \
理想情况下,我想拥有漫游路径......
...喜欢C:\ Users \ myusername \ AppData \ Roaming \
当我在控制台程序中使用以下内容时,我得到了正确的用户目录...
System.Environment.GetEnvironmentVariable("USERPROFILE");
...但是当我在服务中使用相同的变量时,我得到了...
C:\ WINDOWS \ system32 \设置\ systemprofile
如何从服务中获取用户文件夹甚至漫游文件夹位置?
提前谢谢。
答案 0 :(得分:2)
除非将服务配置为使用特定用户的配置文件,否则服务不会像用户一样登录。所以它不会指向“用户”文件夹。
答案 1 :(得分:0)
首先,您需要使用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
答案 2 :(得分:0)
我搜索了从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;
}
}