문제

I need to spawn a process with elevated privileges which would cause a UAC prompt to pop up for the user:

using (process = new Process())
{
    process.StartInfo.FileName = fileName;
    process.StartInfo.Arguments = string.Join(" ", arg1, arg2, arg3);
    process.StartInfo.Verb = "runas";
    process.Start();
}

The problem that I'm having is that if the user selects 'no' in the UAC prompt, the process object will throw an exception stating that 'The operation was canceled by the user.' If the user selects no, then the parent process should just continue as normal (the spawned process is completely optional). Is there a better way of handling this scenario other than just catching the exception and doing nothing?

도움이 되었습니까?

해결책

What else would you want to do instead of catching the exception and doing nothing? That is the only thing that I can think about.

다른 팁

You need to catch the error and if you use a background worker you won't get any exception error. Nevertheless, It is still bad practice not to catch exceptions separately.

Here is how It's done:

try
{
    //your code here
        using (process = new Process())
            {
                process.StartInfo.FileName = fileName;
                process.StartInfo.Arguments = string.Join(" ", arg1, arg2, arg3);
                process.StartInfo.Verb = "runas";
                process.Start();

            }
    //end code
}
catch(System.ComponentModel.Win32Exception)
{
//Do Something or Leave it empty to swallow the exception
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top