0

I have a windows form (setup project) that I developed in c#. Since some users in the domain are not authorized to install the program, they need to right click on the exe and select run as administrator and install. For the exe to run when the computers are rebooted, I assign the startup folder as follows:

string fileMonitUpService = @"C:\Users\"
    + Environment.GetEnvironmentVariable("USERNAME")
    + @"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\myExe.lnk";

if (!System.IO.File.Exists(fileMonitUpService))
{
    WshShell wshShell = new WshShell();
    IWshRuntimeLibrary.IWshShortcut shortcut;

    string startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

    // Create the shortcut
    shortcut = (IWshRuntimeLibrary.IWshShortcut)wshShell.CreateShortcut(fileMonitUpService);

    shortcut.TargetPath = root + "\\" + "Myexe.exe";
    shortcut.WorkingDirectory = Application.StartupPath;
    shortcut.Description = "MyExe.exe";
    shortcut.Save();
}

The problem is that when I right click and select Run with Admin, it assigns the admin user's home folder. I cannot get the name of the current user who opened Windows. Also, I couldn't shoot with the following codes:

System.Windows.Forms.SystemInformation.UserName;
System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • 1
    The behavior is correct, since the "current user" when you elevate is the admin now. – Alejandro Mar 01 '21 at 20:21
  • 3
    The typical approach which is used by installers, is to run as ordinal user, collect the information needed, then to run another instance with elevation (as admin) with passing previously collected information to the elevated instance. But I'm unsure if this applicable in situation with domain and specific permissions. – Serg Mar 01 '21 at 21:21
  • It seems similar to getting a current desktop session if a service is running. For example, these posts may provide some useful ideas: 1) https://stackoverflow.com/questions/7065561/from-windowsservice-how-can-i-find-currently-logged-in-user-from-c and 2) https://stackoverflow.com/questions/34992883/c-sharp-windows-service-get-the-current-logged-user-desktop-directory-path – Loathing Mar 02 '21 at 05:37

1 Answers1

2

You might try WMI and see if this works (if you don't have it referenced there is a Nuget package for it).

string username;

using (var searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem"))
{
    using (var collection = searcher.Get())
    {
        username = collection.Cast<ManagementBaseObject>().First()["UserName"].ToString();
    }
}
b.pell
  • 3,873
  • 2
  • 28
  • 39