【问题标题】:c# windows form, When I run as admin, I cant get the current usernamec# windows窗体,当我以管理员身份运行时,我无法获取当前用户名
【发布时间】:2021-03-01 20:13:11
【问题描述】:

我有一个用 c# 开发的 windows 窗体(安装项目)。由于域中的某些用户无权安装该程序,因此他们需要右键单击该exe并选择以管理员身份运行并安装。为了在计算机重新启动时运行 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();
}

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

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

【问题讨论】:

  • 行为是正确的,因为你提升时的“当前用户”现在是管理员。
  • 安装程序使用的典型方法是以序号用户身份运行,收集所需信息,然后以提升(以管理员身份)运行另一个实例,并将先前收集的信息传递给提升的实例。但我不确定这是否适用于具有域和特定权限的情况。
  • 如果服务正在运行,这似乎类似于获取当前桌面会话。例如,这些帖子可能会提供一些有用的想法:1)stackoverflow.com/questions/7065561/… 和 2)stackoverflow.com/questions/34992883/…

标签: c# windows winforms


【解决方案1】:

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

string username;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多