简体   繁体   中英

How to let my program access a file in System32?

I want to make a C# program that deletes a file in system32. The program can delete a file in an normally accessed area such as the desktop but won't find a file in system32, how would I give the program access to system32? Here's my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string filepath = @"C:\Windows\System32\New.txt";
            if (File.Exists(filepath))
                {
                     File.Delete(filepath);
                }
            else
                {
                Console.WriteLine("File not found");
                Console.ReadLine();
                }
        }
    }
}

To begin with you SHOULD NOT delete files from system 32 folder, these files usually belong to OS and should not be tempered with.
Anyways ! i would not ask why you have this requirement but windows User Account Control (UAC) will not allow you perform this operation just like that, You will need to elevate the permissions and take ownership of the file as shown below :

    //take ownership of the file, code assumes file you want to delete is toBeDeleted.txt
    ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", @"/k takeown /f C:\Windows\System32\toBeDeleted.txt && icacls C:\Windows\System32\toBeDeleted.txt /grant %username%:F");
    processInfo.UseShellExecute = true;
    processInfo.Verb = "runas";
    processInfo.FileName = fileName;//path of your executable
    try
    {
        Process.Start(processInfo);
        // a prompt will be presented to user continue with deletion action
        // you may want to have some other checks before deletion
        File.Delete(@"C:\Windows\System32\toBeDeleted.txt");
        return true;
    }
    catch (Win32Exception)
    {
        //Do nothing as user cancelled UAC window.
    }  

When you run this a prompt will be presented to user to confirm this action, if you want to avoid this you'll need to run your entire host process with elevated permissions by Creating and Embedding an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.

Hope this helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM