Search code examples
c#asp.netterminal-services

Find Terminal Services user's document folder


I'm trying to allow users to use their local scanners with a Terminal Server via an IIS aspx page containing a browser plugin. The plugin can scan files and pass the data to an aspx page which uploads files to the server.

I'm using HttpContext.Current.User.Identity.Name to get a string containing the name of the remote user. How can I find the user's documents folder on the terminal server?


Solution

  • Made a bit of progress. Here's a way to find a the path for a known username using Powershell:

    $user = Get-WmiObject Win32_UserAccount | Where-Object { $_.Name -eq 'known_username' }
    cd 'HKLM:\software\Microsoft\Windows NT\CurrentVersion\ProfileList'
    $key = Get-Item $user.SID
    $saveLocation = $key.GetValue("ProfileImagePath")
    

    Here's the C# version:

    string loginName = HttpContext.Current.User.Identity.Name;
    Regex r = new Regex(@"\w+[\\]");
    string userName = r.Replace(loginName, "");
    throw new System.ArgumentException("Debug: '" + HttpContext.Current.User.Identity.IsAuthenticated.ToString() +"'", "userName");
    SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "name='" + userName + "'");
    ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
    string sid = "";
    foreach (ManagementObject mObject in mSearcher.Get()) 
    {
        sid = mObject["SID"].ToString();
        break; //mSearcher.Get() is not indexable. Behold the hackyness!
    }
    string saveLocation = Microsoft.Win32.Registry.GetValue(
        "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\" + sid,
        "ProfileImagePath", null).ToString();
    

    C# is not my native tongue; there are probably methods of accomplishing this that are less blunt. But it does work.