namespace PermissionTest
{
public class PermissionControl
{
List usernames = new List();
List adminusers = new List();
string file_path = "C:\\TEXT1.txt";
public PermissionControl()
{
try
{
GetALLUsersList();
Load_Admin_Users();
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
RemoveAccess(file_path);
}
// -- this function all the users of the system on the generic list --
private void GetALLUsersList()
{
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName == "User")
{
usernames.Add(child.Name);
}
}
}
// -- this function admin users of the system on the generic list --
private void Load_Admin_Users()
{
using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
{
foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
{
using (DirectoryEntry memberEntry = new DirectoryEntry(member))
{
adminusers.Add(memberEntry.Name);
//Console.WriteLine(memberEntry.Name);
}
}
}
//Console.ReadKey();
}
//--- this method is used to remove access of non admin users on a file --
private void RemoveAccess(string FilePath)
{
try
{
FileSecurity fs = File.GetAccessControl(FilePath);
foreach (string uname in usernames)
{
if (adminusers.Contains(uname) == false)
{
try
{
fs.AddAccessRule(new FileSystemAccessRule(System.Environment.UserDomainName + "\\" + uname, FileSystemRights.FullControl, AccessControlType.Deny));
File.SetAccessControl(FilePath, fs);
}
catch (System.Security.SecurityException se)
{
MessageBox.Show(se.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
MessageBox.Show("Admin Permissions applied.", "Test");
// @System.Environment.UserDomainName\AccountName"
// "denied from FullControl access.");
}
}
static class Program
{
static string LogFile = Application.StartupPath + "\\LogFile.txt";
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
//Application.EnableVisualStyles();
//Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new PermissionTest ());
// Execute the command synchronously.
// first of create a log file
if (!File.Exists(LogFile))
{
File.Create(LogFile);
}
PermissionControl p = new PermissionControl();
}
}
}
No comments:
Post a Comment