2012-04-24 46 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