Faruk Durak
Faruk Durak

Reputation: 95

c# windows form, When I run as admin, I cant get the current username

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;

Upvotes: 0

Views: 636

Answers (1)

b.pell
b.pell

Reputation: 4318

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();
    }
}

Upvotes: 2

Related Questions