2009-10-28 103 views

回答

6

實現它的方法是創建一個從System.Configuration.Install.Installer派生的類。覆蓋Install()方法。以下是更改目錄和文件權限的示例,您可能不想這麼放任,但這取決於您的安全上下文。爲了達到這個目的,安裝項目必須將其作爲自定義操作運行。從該類所在的任何項目中添加「主輸出」。您還需要將目錄傳遞到其屬性中的自定義操作。第一個變量名必須與代碼匹配。像這樣:/targetdir="[TARGETDIR]\"

[RunInstaller(true)] 
public partial class SetPermissions : Installer 
{ 
    private const string STR_targetdir = "targetdir"; 
    private const string STR_aspnetUser = "ASPNET"; 

    public SetPermissions() 
    { 
     InitializeComponent(); 
    } 

    public override void Install(IDictionary stateSaver) 
    { 
     base.Install(stateSaver); 

     Context.LogMessage(
      Context.Parameters 
       .Cast<DictionaryEntry>() 
       .Select(entry => String.Format("String = {0} Value = {1}", entry.Key, entry.Value)) 
       .Aggregate(new StringBuilder("From install\n"), (accumulator, next) => accumulator.AppendLine(next)) 
       .ToString() 
     ); 

     string targetDir = Context.Parameters[STR_targetdir]; 
     string dbDir = Path.Combine(targetDir, "db"); 

     AddFullControlPermissionToDir(dbDir, STR_aspnetUser); 
     string rimdbSqliteFilename = Path.Combine(dbDir, "db.sqlite"); 
     AddFullControlPermissionToFile(rimdbSqliteFilename, STR_aspnetUser); 
     string logsDir = Path.Combine(targetDir, "logs"); 
     AddFullControlPermissionToDir(logsDir, STR_aspnetUser); 
    } 

    private static void AddFullControlPermissionToDir(string dir, string user) 
    { 
     DirectorySecurity directorySecurity = Directory.GetAccessControl(dir); 
     directorySecurity.AddAccessRule(
      new FileSystemAccessRule(
       user, 
       FileSystemRights.FullControl, 
       InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
       PropagationFlags.None, 
       AccessControlType.Allow)); 
     Directory.SetAccessControl(dir, directorySecurity); 
    } 

    private static void AddFullControlPermissionToFile(string filename, string user) 
    { 
     FileSecurity fileSecurity = File.GetAccessControl(filename); 
     fileSecurity.AddAccessRule(
      new FileSystemAccessRule(
       user, 
       FileSystemRights.FullControl, 
       AccessControlType.Allow)); 
     File.SetAccessControl(filename, fileSecurity); 
    } 
} 
+0

您節省了一大堆時間。謝謝一堆! – kakopappa

+3

感謝您的完整代碼示例,節省了一大堆時間。我在實現這個動作時學到了兩件事:1)如果你在TARGETDIR中有空格,你需要像這樣傳遞它:/ targetdir =「[TARGETDIR] \」當然,嘗試引號顯然很明顯,最後一個! (http://msdn.microsoft.com/en-us/library/2w2fhwzz%28VS.80%29.aspx)我學到的另一件事是,要調試一個操作,可以方便地打斷並附加調試器,如下所示:System .Diagnostics.Debugger.Launch(); –