首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >作为系统帐户运行的Windows服务如何获得当前用户的\AppData\Local\专用文件夹?

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

Stack Overflow用户
提问于 2022-11-29 15:08:53
回答 1查看 35关注 0票数 -1

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

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

理想情况下,我会用这样的方法

代码语言:javascript
复制
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

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

但是,由于我的windows服务以系统形式运行(不能更改),所以该方法将返回: C:\Windows\system32\config\systemprofile\AppData\Local。

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

EN

回答 1

Stack Overflow用户

发布于 2022-11-29 20:11:50

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

添加引用:System.Management

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

UserInfo.cs

代码语言:javascript
复制
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;
    }
}

GetLoggedInUserInfo

代码语言:javascript
复制
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;
}

使用

代码语言:javascript
复制
List<UserInfo> users = GetLoggedInUserInfo();

资源

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74616146

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档