繁体   English   中英

作为系统帐户运行的 Windows 服务如何获取当前用户的 \AppData\Local\ 特殊文件夹?

[英]How can Windows service running as System account get current user's \AppData\Local\ special-folder?

我的应用程序是一个 windows 桌面 exe 和 windows 服务,它在系统帐户下运行。 我的 windows 服务需要与用户还将安装的第三方应用程序集成,该应用程序将一些配置信息存储在windows 特殊文件夹之一的 ini 文件中:C:\Users\[UserName]\AppData\Local\[第 3 方应用名称]

当 windows 服务作为系统帐户运行时,我的 Windows 服务如何检索当前用户到该文件夹的路径以读取其中的 ini 文件?

理想情况下,我会使用类似

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

从以当前用户身份运行的应用程序运行时,它会返回正确的\AppData\Local\文件夹。

但是因为我的 windows 服务作为 SYSTEM 运行(无法更改),该方法反而返回:C:\Windows\system32\config\systemprofile\AppData\Local

那么我的windows服务如何获取当前登录用户的LocalApplicationData特殊文件夹呢?

下面的代码显示了如何获取登录用户列表。 获得登录用户列表后,您可以检查您感兴趣的文件 ( File.GetLastWriteTime ) 的最后更新时间。

添加参考:System.Management

创建一个class (名称:UserInfo.cs)

用户信息.cs

public class UserInfo : IComparable<UserInfo>
{
    public string Caption { get; set; }
    public string DesktopName { get; set; }
    public string Domain { get; set; }
    public bool IsLocalAccount { get; set; } = false;
    public bool IsLoggedIn { get; set; } = false;
    public bool IsRoamingConfigured { get; set; } = false;
    public DateTime LastUploadTime { get; set; }
    public DateTime LastUseTime { get; set; }
    public string LocalPath { get; set; }
    public bool IsProfileLoaded { get; set; } = false;
    public string ProfilePath { get; set; }
    public string SID { get; set; }
    public uint SIDType { get; set; }
    public string Status { get; set; }
    public string Username { get; set; }

    public int CompareTo(UserInfo other)
    {
        //sort by name
        if (this.Caption == other.Caption)
            return 0;
        else if (String.Compare(this.Caption, other.Caption) > 1)
            return 1;
        else
            return -1;
    }

    public override string ToString()
    {
        string output = string.Empty;
        output += $"Caption: '{Caption}'{Environment.NewLine}";
        output += $"Domain: '{Domain}'{Environment.NewLine}";
        output += $"Username: '{Username}'{Environment.NewLine}";
        output += $"IsProfileLoaded: '{IsProfileLoaded}'{Environment.NewLine}";
        output += $"IsRoamingConfigured: '{IsRoamingConfigured}'{Environment.NewLine}";
        output += $"LocalPath: '{LocalPath}'{Environment.NewLine}";
        output += $"LastUseTime: '{LastUseTime.ToString("yyyy/MM/dd HH:mm:ss")}'{Environment.NewLine}";
        output += $"SID: '{SID}'{Environment.NewLine}";

        return output;
    }
}

获取登录用户信息

public List<UserInfo> GetLoggedInUserInfo()
{
    List<UserInfo> users = new List<UserInfo>();

    //create reference
    System.Globalization.CultureInfo cultureInfo = System.Globalization.CultureInfo.CurrentCulture;

    using (ManagementObjectSearcher searcherUserAccount = new ManagementObjectSearcher("SELECT Caption, Domain, LocalAccount, Name, SID, SIDType, Status FROM Win32_UserAccount WHERE Disabled = false"))
    {
        foreach (ManagementObject objUserAccount in searcherUserAccount.Get())
        {
            if (objUserAccount == null)
                continue;

            //create new instance
            UserInfo userInfo = new UserInfo();

            string caption = objUserAccount["Caption"].ToString();

            //set value
            userInfo.Caption = caption;
            userInfo.Domain = objUserAccount["Domain"].ToString();

            userInfo.IsLocalAccount = (bool)objUserAccount["LocalAccount"];
            userInfo.Username = objUserAccount["Name"].ToString();

            string sid = objUserAccount["SID"].ToString();

            userInfo.SID = sid;
            userInfo.SIDType =  Convert.ToUInt32(objUserAccount["SIDType"]);
            userInfo.Status = objUserAccount["Status"].ToString();

            using (ManagementObjectSearcher searcherUserProfile = new ManagementObjectSearcher($"SELECT LastUseTime, LastUploadTime, Loaded, LocalPath, RoamingConfigured FROM Win32_UserProfile WHERE SID = '{sid}'"))
            {
                foreach (ManagementObject objUserProfile in searcherUserProfile.Get())
                {
                    if (objUserProfile == null)
                        continue;

                    if (objUserProfile["LastUploadTime"] != null)
                    {
                        string lastUploadTimeStr = objUserProfile["LastUploadTime"].ToString();

                        if (lastUploadTimeStr.Contains("."))
                            lastUploadTimeStr = lastUploadTimeStr.Substring(0, lastUploadTimeStr.IndexOf("."));

                        DateTime lastUploadTime = DateTime.MinValue;

                        //convert DateTime
                        if (DateTime.TryParseExact(lastUploadTimeStr, "yyyyMMddHHmmss", cultureInfo, System.Globalization.DateTimeStyles.AssumeUniversal, out lastUploadTime))
                            userInfo.LastUseTime = lastUploadTime;

                        //set value
                        userInfo.LastUploadTime = lastUploadTime;
                    }


                    string lastUseTimeStr = objUserProfile["LastUseTime"].ToString();

                    if (lastUseTimeStr.Contains("."))
                        lastUseTimeStr = lastUseTimeStr.Substring(0, lastUseTimeStr.IndexOf("."));

                    DateTime lastUseTime = DateTime.MinValue;

                    //convert DateTime
                    if (DateTime.TryParseExact(lastUseTimeStr, "yyyyMMddHHmmss", cultureInfo, System.Globalization.DateTimeStyles.AssumeUniversal, out lastUseTime))
                        userInfo.LastUseTime = lastUseTime;

                    //Debug.WriteLine($"LastUseTime: '{objUserProfile["LastUseTime"].ToString()}' After Conversion: '{lastUseTime.ToString("yyyy/MM/dd HH:mm:ss")}'");

                    userInfo.LocalPath = objUserProfile["LocalPath"].ToString();
                    userInfo.IsProfileLoaded = (bool)objUserProfile["Loaded"];
                    userInfo.IsRoamingConfigured = (bool)objUserProfile["RoamingConfigured"];
                }
            }

            if (userInfo.IsProfileLoaded)
            {
                Debug.WriteLine(userInfo.ToString());

                //add
                users.Add(userInfo);
            }
        }
    }

    //sort by LastUseTime
    users.Sort(delegate (UserInfo info1, UserInfo info2) { return info1.LastUseTime.CompareTo(info2.LastUseTime); });

    return users;
}

用法

List<UserInfo> users = GetLoggedInUserInfo();

资源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM