如何让我的程序访问System32中的文件?

问题描述:

我想制作一个删除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(); 
       } 
     } 
    } 
} 
+4

Windows目录树中的文件不能由非管理员用户写入,即使是管理员用户也需要特别同意。 Windows目录下的文件属于操作系统,而不是用户。 IOW,你*不*给予程序访问权限,因为该程序不是操作系统的一部分。 Windows还保护系统文件,如果您尝试删除或替换它们,它们将恢复它们。这是一种反恶意软件机制。 –

+3

您需要在具有足够权限执行您想要的操作的用户帐户下运行您的程序。 –

+1

不建议从system32中删除文件。 – Amy

首先,你不应该删除系统32文件夹中的文件,这些文件通常属于操作系统,不应与回火。
反正!我不会问为什么你有这个要求,但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. 
    } 

当你运行这个提示时,会提示用户确认这个动作,如果你想避免这种情况,你需要运行你的整个主机进程的权限为Creating and Embedding an Application Manifest (UAC),以要求'highestAvailable'执行级别:这将会在应用程序启动后立即显示UAC提示,并使所有子进程以提升的权限运行,而无需其他提示。

希望这会有所帮助!