【问题标题】:Need to delete files in Program files using c#, files wont delete需要使用c#删除Program files中的文件,文件不会删除
【发布时间】:2012-05-05 10:39:29
【问题描述】:

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

【问题讨论】:

  • 从提升的命令提示符运行它。
  • 好吧,这将被注入一个从 exe 运行的程序中,我得看看你的说法,exe 必须以管理员身份运行,然后不是?

标签: c# admin delete-file


【解决方案1】:

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

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      为了从“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
      

      【讨论】:

      • 啊酷,我想没有办法绕过用户选择,因为它是 Windows 中的一项安全功能?
      猜你喜欢
      • 2010-12-21
      • 2010-12-13
      • 1970-01-01
      • 2018-03-30
      • 2012-02-24
      • 2017-01-06
      • 1970-01-01
      • 2015-03-20
      • 2019-02-14
      相关资源
      最近更新 更多