[英]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 \\設置\\ systemprofile
如何從服務中獲取用戶文件夾甚至漫游文件夾位置?
提前致謝。
除非將服務配置為使用特定用戶的配置文件,否則服務不會像用戶那樣登錄。 因此,它不會指向“用戶”文件夾。
首先,您將要使用Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Environment.SpecialFolder.ApplicationData
用於漫游配置文件。
在此處查找所有SpecialFolder枚舉值: https ://msdn.microsoft.com/zh-cn/library/system.environment.specialfolder( v= vs.110).aspx
如其他人所述,該服務將在帳戶LocalSystem / LocalService / NetworkService下運行,具體取決於配置: https : //msdn.microsoft.com/zh-cn/library/windows/desktop/ms686005(v=vs.85)的.aspx
我已經搜索了從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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.