Search code examples
c#privilegessharpziplib

Request admin privileges to edit system files


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?


Solution

  • 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:

    enter image description here

    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>