我有这个应用程序需要在受保护的路径中做一些事情(比如%PROGRAMFILES%),我知道我应该使用%APPDATA%,但我暂时无法改变它。我已经隔离了所有可能需要UAC出现在另一个项目上的东西,这里是一个示例代码:

using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

class Class1
{
    static void Main(string[] args)
    {
        try
        {
            File.CreateText(Path.Combine(Application.StartupPath, "something.txt"));
        }
        catch (UnauthorizedAccessException ex)
        {
            MessageBox.Show(ex.Message, "UnauthorizedAccessException", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (args.Length == 0)
            {
                Process proc = new Process();
                proc.StartInfo.FileName = Application.ExecutablePath;
                proc.StartInfo.Arguments = "not again";
                proc.StartInfo.Verb = "runas";
                proc.Start();
            }
            else
            {
                MessageBox.Show("Exit to avoid loop.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

因此,我从我的主程序中调用此可执行文件,如果由于未经授权的访问而失败,它将自动启动显示UAC请求。

我的问题是:

1)我不得不将项目输出从DLL转换为EXE,因为我找不到任何方法从DLL请求UAC提升,有没有简单的方法呢?

2)我还注意到有些程序会显示个性化的UAC消息,包含程序徽标和所有这些内容,让我给大家展示一个例子:

我如何为我的计划做到这一点?

3)为了避免在使用提升的权限运行时进入循环,它会获得另一个UnauthorizedAccessException我做了那个传递任何args的东西。你会怎样做才能达到同样的目标?

我认为现在一切都好。谢谢你的时间。

有帮助吗?

解决方案

1您无法控制托管DLL的进程的提升模式。您可以授予目标文件夹或注册表的权限如果您可以控制安装过程,则为每个人在安装过程中

2你需要使用由客户端信任的证书颁发机构发布的证书对程序进行签名。访问您当地的证书商店(控制面板 - >互联网选项,内容标签,发布商),以查看常见的证书颁发机构。

3当您获得UnauthorizedAccessExceotion时,将其抛给托管exe或返回指示安全问题的错误值。然后,DLL的调用者决定要做什么,例如显示安全错误对话框以通知用户程序是否已被提升(域控制器未授予权限?)或如果没有提升,则使用runas命令以提升模式重启进程

其他提示

我有同样的问题。谷歌搜索大约2天我找到了唯一符合我需求的解决方案 - 以管理权限启动应用程序。我启动应用程序,检查它是否以管理员身份运行。如果没有 - 重新启动它具有管理权限。

    static void Main(string[] args)
    {
        if (NeedElevation(args) && Elevate(args))
        { // If elevastion succeeded then quit.
            return;
        }
        // your code here
    }

    public static bool Elevate(string[] args)
    {
        try
        {
            ProcessStartInfo info = Process.GetCurrentProcess().StartInfo;
            info.Verb = "runas";
            info.Arguments = NoElevateArgument;
            foreach (string arg in args)
            {
                info.Arguments += ' ' + arg;
            }
            info.FileName = Assembly.GetEntryAssembly().Location;

            Process process = new System.Diagnostics.Process();
            process.StartInfo = info;

            process.Start();
        }
        catch (Exception)
        {
            MessageBox.Show("You don't have administrative privileges thus the Automatic Application Updates cannot be started. But the rest of application is available as usually.",
                "Not enough user rights", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return false;
        }

        return true;
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top