0

为什么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); }
            }
        }
    }
}
4

3 回答 3

3

你需要重新考虑你的策略。

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

  1. 比如用户的数据目录/你的公司/你的应用程序,或者
  2. 用户的文件/您的公司/您的应用程序

Program Files 目录用于存储与程序一起安装但安装/更新后不会更改的应用程序特定文件(DLL 等)。

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

public static DirectoryInfo ApplicationVersionDirectory()
{
    return new DirectoryInfo(System.Windows.Forms.Application.UserAppDataPath);
}
于 2012-04-24T19:00:28.343 回答
2

这是由于 UAC。因此,要么通过右键单击以管理员身份运行您的可执行文件 - >“以管理员身份运行”,或者如果您想以编程方式执行它,请参阅其他帖子,如Windows 7 和 Vista UAC - 以编程方式请求 C# 中的提升

于 2012-04-24T18:40:47.790 回答
0

为了从“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
于 2012-04-24T18:44:53.790 回答