繁体   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