How to get admin privileges for editing app.config in C#?

后端 未结 3 593
一向
一向 2021-01-16 11:14

I\'ve got a program which uses app.config for storing some preferences. The problem is that if the program is installed in C:\\program files\\ t

3条回答
  •  别那么骄傲
    2021-01-16 12:15

    To answer your question, as-is, there is no way to 'temporarily' elevate. The app must be launched with an elevation request.

    Typically, if an app normally needs no elevation, you would break out the functionality that needs elevation into a mode controlled by a switch and then launch itself with a runas verb.

    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.UseShellExecute = true;
    startInfo.WorkingDirectory = Environment.CurrentDirectory;
    startInfo.FileName = Application.ExecutablePath;
    startInfo.Arguments = "-doSomethingThatRequiresElevationAndExit";
    startInfo.Verb = "runas";
    try
    {
        Process p = Process.Start(startInfo);
        p.WaitForExit();
    
    }
    catch(System.ComponentModel.Win32Exception ex)
    {
        return;
    }
    

    But, you might want to place config settings that a user may want to modify as user-scoped so that the config resides in their appData directory thus requiring no elevation.

提交回复
热议问题