.NET 애플리케이션을 관리자 권한으로 실행하려면 어떻게해야합니까?
내 프로그램이 클라이언트 컴퓨터에 설치되면 내 프로그램을 Windows 7에서 관리자 권한으로 실행하려면 어떻게해야합니까?
프로그램에 포함되는 매니페스트를 수정하고 싶을 것입니다. 이것은 Visual Studio 2008 이상에서 작동합니다 : 프로젝트 + 새 항목 추가, "응용 프로그램 매니페스트 파일"을 선택합니다. <requestedExecutionLevel>
요소를 다음으로 변경하십시오 .
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
사용자는 프로그램을 시작할 때 UAC 프롬프트를 받습니다 . 현명하게 사용하십시오. 그들의 인내심은 빨리 닳을 수 있습니다.
requestedExecutionLevel
매니페스트에 요소를 추가하는 것은 전투의 절반에 불과합니다. UAC 를 끌 수 있음 을 기억해야 합니다. 만약 그렇다면, 당신은 구식 방식으로 확인을 수행하고 사용자가 관리자가 아닌 경우 오류 대화 상자를 표시해야합니다
( IsInRole(WindowsBuiltInRole.Administrator)
스레드의를 호출 하십시오 CurrentPrincipal
).
세부 단계는 다음과 같습니다.
- 솔루션에 애플리케이션 매니페스트 파일 추가
- 애플리케이션 설정을 "app.manifest"로 변경
- requireAdministrator로 "requestedExecutionLevel"태그를 업데이트하십시오.
이 코드를 사용하려면 ClickOnce의 보안 설정을 해제해야합니다. 이렇게하려면 속성-> 보안-> ClickOnce 보안으로 이동합니다.
수동으로 수행하는 코드를 구현했습니다.
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
You can embed a manifest file in the EXE file, which will cause Windows (7 or higher) to always run the program as an administrator.
You can find more details in Step 6: Create and Embed an Application Manifest (UAC) (MSDN).
While working on Visual Studio 2008, right click on Project -> Add New Item
and then chose Application Manifest File
.
In the manifest file, you will find the tag requestedExecutionLevel
, and you may set the level to three values:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
OR
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
OR
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
To set your application to run as administrator, you have to chose the middle one.
As per
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
you will want to add an application manifest if you don't already have one or don't know how to add one. As some projects don't automatically add a separate manifest file, first go to project properties, navigate to the Application tab and check to make sure your project is not excluding the manifest at the bottom of the tap.
- Next, right click project
- Add new Item
- Last, find and click Application Manifest File
In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin
is a method that detects if under current conditions admin privileges are required. If this returns false
the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
This is a simplified version of the this answer, above by @NG
public bool IsUserAdministrator()
{
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
You can create the manifest using ClickOnce Security Settings, and then disable it:
Right click on the Project -> Properties -> Security -> Enable ClickOnce Security Settings
After you clicked it, a file will be created under the Project's properties folder called app.manifest once this is created, you can uncheck the Enable ClickOnce Security Settings
option
Open that file and change this line :
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will make the program require administrator privileges.
Right click your executable, go to Properties > Compatibility and check the 'Run this program as admin' box.
If you want to run it as admin for all users, do the same thing in 'change setting for all users'.
'Nice programing' 카테고리의 다른 글
야, 내 php.ini는 어딨어? (0) | 2020.09.28 |
---|---|
npm은 어디에 패키지를 설치합니까? (0) | 2020.09.28 |
두 위도-경도 지점 사이의 거리를 계산 하시겠습니까? (0) | 2020.09.28 |
.css () 함수로 추가 된 스타일을 제거하려면 어떻게해야합니까? (0) | 2020.09.28 |
함수 이름 앞에 JavaScript 더하기 기호 (0) | 2020.09.28 |