簡體   English   中英

如何讓我的程序訪問System32中的文件?

[英]How to let my program access a file in System32?

我想制作一個C#程序來刪除system32中的文件。 該程序可以刪除通常訪問的區域(例如桌面)中的文件,但在system32中找不到文件,我如何授予程序對system32的訪問權限? 這是我的代碼:

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();
                }
        }
    }
}

首先,您不應該從系統32文件夾中刪除文件,這些文件通常屬於OS,因此請勿使用。
無論如何 ! 我不會問您為什么有此要求,但是Windows用戶帳戶控制(UAC)不允許您像這樣執行此操作,您將需要提升權限並取得文件的所有權,如下所示:

    //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.
    }  

運行此命令時,系統將提示用戶確認此操作,如果要避免此操作,則需要通過創建和嵌入應用程序清單(UAC)以要求'highestAvailable '執行級別:這將導致UAC提示在您的應用程序啟動后立即出現,並使所有子進程以提升的權限運行,而無需其他提示。

希望這可以幫助 !

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM