Preventing user to remove and rename any directories with sub directories and files
In this article I will explain you that how you can create security for your important folders (directories) which may contains folders (directories) and files. By changing the file system access rules, file system rights, access control type, etc. I will explain you all the things in detail.
Purpose : To keep safe important files and folders
Overview : Keep files and folder to Freezing and Unfreezing mode. I have used MS Access database to work this application anywhere without sql server dependency
Step 1 : Create three forms
I have created forms like : Login, Master and Report
Login Form
Step 2 : Write the below mentioned code on login form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Application.StartupPath + "\\DBDetails.accdb" + "';Persist Security Info=True;Jet OLEDB:Database Password=Abcd1234;");
string username, password;
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void txtUsername_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
if (txtUsername.Text == string.Empty || txtUsername.Text == "" || txtUsername.Text == null)
txtUsername.Focus();
else
SendKeys.Send("{TAB}");
}
}
private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
if (txtPassword.Text == string.Empty || txtPassword.Text == "" || txtPassword.Text == null)
txtPassword.Focus();
else
btnLogin_Click(btnLogin, null);
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text == string.Empty || txtUsername.Text == "" || txtUsername.Text == null)
{
MessageBox.Show("Username required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUsername.Focus();
}
else if (txtPassword.Text == string.Empty || txtPassword.Text == "" || txtPassword.Text == null)
{
MessageBox.Show("Password required", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPassword.Focus();
}
else
{
// Checking if connection is opened. If it is open than close it
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Login WHERE Username = '" + txtUsername.Text.Trim() + "'", con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
username = dr[0].ToString();
password = dr[1].ToString();
dr.Close();
}
if (txtUsername.Text.Trim() == username && txtPassword.Text.Trim() == password)
{
txtUsername.Clear();
txtPassword.Clear();
txtUsername.Focus();
Master m = new Master();
this.Hide();
m.ShowDialog();
}
else
{
MessageBox.Show("Username or password doesn't match.", "Invalid Credential Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUsername.Focus();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
Master Form
Step 3 : Write the below mentioned code on master form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.AccessControl;
using System.Data.OleDb;
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Application.StartupPath + "\\DBDetails.accdb" + "';Persist Security Info=True;Jet OLEDB:Database Password=Abcd1234;");
OleDbConnection con1 = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Application.StartupPath + "\\DBDetails.accdb" + "';Persist Security Info=True;Jet OLEDB:Database Password=Abcd1234;");
string selectedpath = null;
string user;
// Method to use shorcut keys at form level
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F5)
{
Report rp = new Report();
rp.ShowDialog();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
public void PathSelection()
{
using (FolderBrowserDialog fd = new FolderBrowserDialog())
{
if (DialogResult.OK == fd.ShowDialog())
{
selectedpath = fd.SelectedPath;
}
}
}
private void PerformDatabaseAction(string query)
{
try
{
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch (OleDbException exc)
{
MessageBox.Show(exc.Source, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Master_Load(object sender, EventArgs e)
{
user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
private void btnLogout_Click(object sender, EventArgs e)
{
Login l = new Login();
this.Hide();
l.ShowDialog();
}
// Freeze the directories
private void btnFreeze_Click(object sender, EventArgs e)
{
try
{
PathSelection();
if (selectedpath != null)
{
// Checking if connection is opened. If it is open then close it
if (con1.State == ConnectionState.Open)
con1.Close();
con1.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM SecurityDetails WHERE FolderPath = '" + selectedpath + "'", con1);
OleDbDataReader dr = cmd1.ExecuteReader();
// Checking if the selected path is freezed or not
if (dr.HasRows != true)
{
// Get folder info and access control of particular directory
System.IO.DirectoryInfo folderInfo = new System.IO.DirectoryInfo(selectedpath);
DirectorySecurity folderSecurity = folderInfo.GetAccessControl();
// Set file system access rules
FileSystemAccessRule rule =
new FileSystemAccessRule(
user,
FileSystemRights.Delete |
FileSystemRights.DeleteSubdirectoriesAndFiles,
InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Deny);
folderSecurity.AddAccessRule(rule);
Directory.SetAccessControl(selectedpath, folderSecurity);
// Insert values to database for reporting purpose
string str = "INSERT INTO SecurityDetails(FolderPath,Status,SysUser) VALUES('" + selectedpath + "','" + btnFreeze.Text + "', '" + user + "')";
PerformDatabaseAction(str);
MessageBox.Show("Directory '" + selectedpath + "' " + btnFreeze.Text + "d successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Directory '" + selectedpath + "' is already " + btnFreeze.Text + "d", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
dr.Close();
con1.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
selectedpath = null;
}
}
// Unfreeze the directories
private void btnUnfreeze_Click(object sender, EventArgs e)
{
try
{
PathSelection();
if (selectedpath != null)
{
// Checking if connection is opened. If it is open then close it
if (con1.State == ConnectionState.Open)
con1.Close();
con1.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT * FROM SecurityDetails WHERE FolderPath = '" + selectedpath + "'", con1);
OleDbDataReader dr = cmd1.ExecuteReader();
// Checking if the selected path is freezed or not
if(dr.HasRows == true)
{
// Get folder info and access control of particular directory
DirectoryInfo folderInfo = new DirectoryInfo(selectedpath);
DirectorySecurity folderSecurity = folderInfo.GetAccessControl();
// Set file system access rules
FileSystemAccessRule rule =
new FileSystemAccessRule(
user,
FileSystemRights.Delete |
FileSystemRights.DeleteSubdirectoriesAndFiles,
InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Deny);
folderSecurity.RemoveAccessRule(rule);
Directory.SetAccessControl(selectedpath, folderSecurity);
// Remove values from database for reporting purpose
string str = "DELETE FROM SecurityDetails WHERE FolderPath = '" + selectedpath + "'";
PerformDatabaseAction(str);
MessageBox.Show("Directory '" + selectedpath + "' " + btnUnfreeze.Text + "d successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Directory '" + selectedpath + "' is already " + btnUnfreeze.Text + "d", "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
dr.Close();
con1.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
selectedpath = null;
}
}
Report Form
Step 4 : Write the below mentioned code on report form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + Application.StartupPath + "\\DBDetails.accdb" + "';Persist Security Info=True;Jet OLEDB:Database Password=Abcd1234;");
// Method to use shorcut keys at form level
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void Report_Load(object sender, EventArgs e)
{
try
{
// Checking if connection is opened. If it is open than close it
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM SecurityDetails", con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
// Adding rows to gridview
while (dr.Read())
{
ReportGridView.Rows.Add(dr[0].ToString(), dr[1].ToString(), dr[2].ToString());
}
dr.Close();
}
else
{
MessageBox.Show("No record(s) found", "Empty Data Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
this.Close();
}
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close();
}
}
Validations and Messages
Click here to download sample application
nice!