2012-04-24 54 views
0

为什么不将测试文件夹中的文件删除?我如何获得管理权限?需要使用c#删除程序文件中的文件,文件将不会删除

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); } 
      } 
     } 
    } 
} 
+2

运行它。 – vcsjones 2012-04-24 18:33:02

+0

好吧,这将被注入到一个程序,从一个EXE运行,生病得看看你的说法,EXE将不得不作为管理员运行,然后否? – jitsuin 2012-04-24 18:37:43

回答

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 
+0

很酷,我想没有办法绕过用户的选择,因为它是Windows中的安全功能? – jitsuin 2012-04-24 18:49:49

3

你需要重新思考自己的战略。

如果要添加/从你的应用程序中的编程方式删除文件,它们应该被存放在一个单独的位置(即不再需要管理员PRIVS提升为写/删除等):

  1. 这样的安装与用户的数据目录/公司/你的应用程序,或
  2. 用户的文档/公司/应用程序

Program Files目录是应用程序特定的文件(DLL的,等等)程序,但不要chan ge一旦安装/更新。

这里的用户数据目录的一个示例通过应用:从提升的命令提示

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

谢谢查克,好主意:) – jitsuin 2012-04-24 21:48:11