我可以使用 C#(MVC 或核心)从 Windows Server 2016 中的 "Windows" 文件夹中删除文件吗?

Can I delete files from "Windows" folder in Windows Server 2016 using C# (MVC or Core)?

在 windows server 2016 中,由于某些原因,我在“Windows”文件夹中创建了一个文本文件,在特殊情况下,我需要从我的 C# MVC 构建的网站中删除它,有什么办法可以使用 C#(MVC 或 Core)做到这一点吗?我知道这是不合逻辑的,但如果适用,我需要它。

您的解决方案的答案相当简单,是的,确实可以删除 Windows 文件或文件夹。然而,这是有代价的!允许应用程序拥有管理员权限可能会导致恶意行为。例如 UAC 绕过其他恶意软件。

要使用 C# 编程删除该文件,您需要做的就是首先 运行 您的应用程序具有管理员权限。这是它的源代码:

using System;
using System.IO;
public class Program {
   public static void Main() {
      String myPath = @"<DRIVE_LETTER>:\Windows\<FILENAME>"; // E.g: @"C:\Windows\MyText.txt";
      try{ // For stability purposes,
          File.Delete(myPath);
      } catch (IOException ERROR){ // If any errors occurs, it will print it out!
          Console.WriteLine(ERROR.Message);
      }
   }
} 

权限风险文档:Risks of Admin Rights

File.Delete 的文档:File.Delete(String) Method C#