Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# service: how to get user profile folder path

I need to get the user directory from within a C# windows service...
...like C:\Users\myusername\
Ideally, I'd like to have the roaming path...
...like C:\Users\myusername\AppData\Roaming\
When I used the following in a console program I got the correct user directory...

System.Environment.GetEnvironmentVariable("USERPROFILE"); 

...but when I use that same variable in a service, I get...
C:\WINDOWS\system32\config\systemprofile
How can I get the user folder and maybe even the roaming folder location from a service?
Thanks in advance.

like image 908
Xi Vix Avatar asked Jul 07 '16 18:07

Xi Vix


2 Answers

I have searched for getting the profile path of user from Windows service. I have found this question, which does not include a way to do it. As I have found the solution, partly based on a comment by Xavier J on his answer, I have decided to post it here for others.

Following is a piece of code to do that. I have tested it on few systems, and it should work on different OSes ranging from Windows XP to 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;
        }
    }
like image 72
Arman Nayyeri Avatar answered Sep 17 '22 16:09

Arman Nayyeri


First, you'll want to use Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

Environment.SpecialFolder.ApplicationData is for roaming profiles.

Find all SpecialFolder enumeration values here: https://msdn.microsoft.com/en-us/library/system.environment.specialfolder(v=vs.110).aspx

As others have noted, the Service will run under the account LocalSystem/LocalService/NetworkService, depending on configuration: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686005(v=vs.85).aspx

like image 36
richkisic Avatar answered Sep 18 '22 16:09

richkisic