Request admin privileges to edit system files

2019-07-11 15:14发布

问题:

New to C#, I'm developing a windows form application inside visual studio. The app uses ICSharpCode.SharpZipLib library to update a zip's content.

When the zip file is inside a non system partition, say like D:\myzip.zip the files gets updated correctly. But, if the zip is in the system partition, C:\myzip.zip the app returns an error; Could not find file C:\myzip.zip even though the file is there!

This has to do with admin privileges because when I run the app as administrator it works.

The question is; how could I enable those privileges by default?

回答1:

You can add app manifest to exact your app to run as administrator (msdn).

Add the following code to your manifest file:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Adding app manifest step by step:

  1. Right-click on the project in the Solution Explorer.
  2. Click Add New Item.
  3. Find and select Application Manifest File:

Edit app manifest file:

 <?xml version="1.0" encoding="utf-8"?>
    <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
      <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
        <security>
          <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">       
            <requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />
          </requestedPrivileges>
        </security>
      </trustInfo>

      <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
        <application>    
        </application>
      </compatibility>
    </asmv1:assembly>


回答2:

you want to enable this by default on you'r computer only right? because on other computer you can't, this what security all about