To add file security to any file following function can be used:
Firstly add the name space:
using System.IO;
using System.Security.AccessControl;
public static void AddFileSecurity(string fileName, string account,FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the current security settings.
FileSecurity fSecurity = File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account,rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
Now you can use this function to add file security to any file or directory. Pass the name of file or directory as fileName. Account can be your current account or any other account. The argument rights can be any valid FileSystemRights (for e.g.: FullControl, Read, Write, Delete, Modify). The argument controlType can be any valid AccessControlType(Allow or Deny).
for e.g.:
AddFileSecurity("D:\music","Everyone",FileSystemRights.Delete,AccessControlType.Deny);
Now above file security added to D:\music ensures that no one can delete the folder. As it means 'Deny' 'Everyone' to 'Delete'
Now you can also deny current user to deny delete on this folder. For this just pass name of current user as the argument account.
To know how to get name of current user click the link below:
http://gsbprogramming.blogspot.in/2014/11/how-to-get-current-application-path.html
Firstly add the name space:
using System.IO;
using System.Security.AccessControl;
public static void AddFileSecurity(string fileName, string account,FileSystemRights rights, AccessControlType controlType)
{
// Get a FileSecurity object that represents the current security settings.
FileSecurity fSecurity = File.GetAccessControl(fileName);
// Add the FileSystemAccessRule to the security settings.
fSecurity.AddAccessRule(new FileSystemAccessRule(account,rights, controlType));
// Set the new access settings.
File.SetAccessControl(fileName, fSecurity);
}
Now you can use this function to add file security to any file or directory. Pass the name of file or directory as fileName. Account can be your current account or any other account. The argument rights can be any valid FileSystemRights (for e.g.: FullControl, Read, Write, Delete, Modify). The argument controlType can be any valid AccessControlType(Allow or Deny).
for e.g.:
AddFileSecurity("D:\music","Everyone",FileSystemRights.Delete,AccessControlType.Deny);
Now above file security added to D:\music ensures that no one can delete the folder. As it means 'Deny' 'Everyone' to 'Delete'
Now you can also deny current user to deny delete on this folder. For this just pass name of current user as the argument account.
To know how to get name of current user click the link below:
http://gsbprogramming.blogspot.in/2014/11/how-to-get-current-application-path.html
No comments:
Post a Comment