Setting permissions and blocking inheritance from C# with SetACL
This sample program shows how to use the COM version of SetACL from C#. In the example, inherited permissions are removed from the directory C:\Test (which must already exist) and everyone is given full access to that directory. An event handler receives all output from SetACL which in this sample is simply printed on the console.
using System;
using SetACLCOMLibrary;
//
// Example program showing how to use the COM server version of SetACL from C#
//
// Author: Helge Klein
// Tested with: Visual Studio 2010, .NET 4
//
// Requirements: 1) SetACL.dll must be present and registered (with regsvr32)
// 2) A reference to SetACL must be added as a COM reference to the Visual Studio project
//
namespace SetACLFromCSharp
{
class Program
{
static int Main(string[] args)
{
// Create a new SetACL instance
SetACLCOMServer setacl = new SetACLCOMServer();
// Attach a handler routine to SetACL's message event so we can receive anything SetACL wants to tell us
setacl.MessageEvent += new _ISetACLCOMServerEvents_MessageEventEventHandler(setacl_MessageEvent);
// Enable sending events
int retCode = setacl.SendMessageEvents(true);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Set the object to process
retCode = setacl.SetObject(@"C:\Test", (int)SE_OBJECT_TYPE.SE_FILE_OBJECT);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Set the action (what should SetACL do?): add an access control entry (ACE)
retCode = setacl.SetAction((int)ACTIONS.ACTN_ADDACE);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Set parameters for the action: Everyone (specified using its well-known SID) full access
retCode = setacl.AddACE("S-1-1-0", "Full", 0, false, (int)ACCESS_MODE.SET_ACCESS, (int)SDINFO.ACL_DACL);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Add another action: configure inheritance from the parent object
retCode = setacl.AddAction((int)ACTIONS.ACTN_SETINHFROMPAR);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Set parameters for the action: block inheritance for the DACL, leave the SACL unchanged
retCode = setacl.SetObjectFlags((int)INHERITANCE.INHPARNOCOPY, (int)INHERITANCE.INHPARNOCHANGE, true, false);
if (retCode != (int)RETCODES.RTN_OK)
return 1;
// Now apply the settings (do the actual work and change permissions)
retCode = setacl.Run();
if (retCode != (int)RETCODES.RTN_OK)
return 1;
return 0;
}
/// <summary>
/// Receives string messages fired as COM events by SetACL
/// </summary>
static void setacl_MessageEvent(string message)
{
// For demo purposes, just print the message
Console.WriteLine(message);
}
}
}