需要使用c#删除程序文件中的文件,文件不会删除

需要使用c#删除程序文件中的文件,文件不会删除,c#,admin,delete-file,C#,Admin,Delete File,为什么测试文件夹中的文件不删除??我如何获得管理员权限 namespace Delete { using System; using System.Windows.Forms; using System.IO; public class Delete { public Delete() { if (Directory.Exists(@"C:\Program Files (x86)\test\"))

为什么测试文件夹中的文件不删除??我如何获得管理员权限

namespace Delete
{
    using System;
    using System.Windows.Forms;
    using System.IO;

    public class Delete
    {
        public Delete()
        {
            if (Directory.Exists(@"C:\Program Files (x86)\test\"))
            {
                string[] filePaths = Directory.GetFiles(@"C:\Program Files (x86)\test\");
                foreach (string file in filePaths) { File.Delete(file); }
            }
        }
    }
}

这是由于UAC。因此,您可以通过右键单击->以管理员身份运行可执行文件,或者如果您想以编程方式运行,请参阅其他帖子,如

这是由于UAC。所以,您可以通过右键单击->以管理员身份运行可执行文件,或者如果您想以编程方式运行,请参阅其他帖子,如

,以便从“Program files”文件夹中删除文件,您需要以管理员身份启动应用程序。否则,您将无法访问%PROGRAMFILES%

以下是重新启动当前应用程序并以管理员身份运行的示例代码:

ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";



try
            {

                Process.Start(proc);

            }

            catch

            {

                // The user refused the elevation.

                // Do nothing and return directly ...

                return;

            }

            Application.Exit();  // Quit itself

为了从“程序文件”文件夹中删除文件,您需要以管理员身份启动应用程序。否则,您将无法访问%PROGRAMFILES%

以下是重新启动当前应用程序并以管理员身份运行的示例代码:

ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.FileName = Application.ExecutablePath;
proc.Verb = "runas";



try
            {

                Process.Start(proc);

            }

            catch

            {

                // The user refused the elevation.

                // Do nothing and return directly ...

                return;

            }

            Application.Exit();  // Quit itself

你需要重新考虑你的策略

如果在应用程序中以编程方式添加/删除文件,则应将其存储在单独的位置(不需要管理员权限来提升文件的写入/删除等):

  • 例如用户的数据目录/您的公司/您的应用程序,或
  • 用户文档/您的公司/您的应用程序
  • Program Files目录用于与程序一起安装但在安装/更新后不会更改的特定于应用程序的文件(DLL等)

    以下是按应用程序列出的用户数据目录示例:

    public static DirectoryInfo ApplicationVersionDirectory()
    {
        return new DirectoryInfo(System.Windows.Forms.Application.UserAppDataPath);
    }
    

    你需要重新考虑你的策略

    如果在应用程序中以编程方式添加/删除文件,则应将其存储在单独的位置(不需要管理员权限来提升文件的写入/删除等):

  • 例如用户的数据目录/您的公司/您的应用程序,或
  • 用户文档/您的公司/您的应用程序
  • Program Files目录用于与程序一起安装但在安装/更新后不会更改的特定于应用程序的文件(DLL等)

    以下是按应用程序列出的用户数据目录示例:

    public static DirectoryInfo ApplicationVersionDirectory()
    {
        return new DirectoryInfo(System.Windows.Forms.Application.UserAppDataPath);
    }
    

    从提升的命令提示符运行它。这将被注入一个从exe运行的程序,我必须看看你说的是什么,exe必须作为管理员运行,然后不?从提升的命令提示符运行它。这将被注入一个从exe运行的程序,我必须看看你说的是什么,exe必须以管理员的身份运行,不?啊,很酷,我想没有办法绕过用户选择,因为它是windows中的一项安全功能?啊,很酷,我想没有办法绕过用户选择,因为它是windows中的一项安全功能?