繁体   English   中英

c# windows 表单,当我以管理员身份运行时,我无法获取当前用户名

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

我有一个在 c# 中开发的 windows 表单(设置项目)。 由于域中的某些用户无权安装程序,因此需要右键单击该exe并以管理员身份运行select并安装。 为了在计算机重新启动时运行 exe,我将启动文件夹分配如下:

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

问题是当我右键单击并 select Run with Admin 时,它会分配管理员用户的主文件夹。 我无法获取打开 Windows 的当前用户的名称。 此外,我无法使用以下代码进行拍摄:

System.Windows.Forms.SystemInformation.UserName;
System.Security.Principal.WindowsIdentity.GetCurrent().Name;

您可以尝试 WMI 并查看它是否有效(如果您没有引用它,则有一个 Nuget package 用于它)。

string username;

using (var searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem"))
{
    using (var collection = searcher.Get())
    {
        username = collection.Cast<ManagementBaseObject>().First()["UserName"].ToString();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM