I'm working on an application which stores some files in the CommonApplicationData
folder. My application has to modify these files. I managed to create a custom action to grant fullcontrol
rights to my application folder in the CommonApplicationData
folder. But this didn't solve the problem for non-admin users. When I log on as a user and try to modify one of these files, I get the "Access Denied" message.
How can I solve this problem? Thanks.
Here is the code which I used in the Custom Action:
public void GetUsers()
{
SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "Domain='" + System.Environment.UserDomainName.ToString() + "'");
try
{
ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
foreach (ManagementObject mObject in mSearcher.Get())
{
Permission(mObject["Name"].ToString());
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void Permission(string user)
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string CompanyFolderPath = Path.Combine(directory, "naseelco\\lms2004");
DirectoryInfo myDirectoryInfo = new DirectoryInfo(CompanyFolderPath);
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
string User = System.Environment.UserDomainName + "\\" + user;
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.FullControl, AccessControlType.Allow));
myDirectoryInfo.SetAccessControl(myDirectorySecurity);
}
EDIT:
For those who would like to know the solution for this problem:
Instead of granting Access Rights to the parent folder, the individual files int that folder are granted Access Rights for each user. The Permission method in the code above has been modified as follows:
private void Permission(string user)
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string filePath = Path.Combine(directory, "naseelco\\lms2004\\fms.txt");
FileSecurity fSecurity = File.GetAccessControl(filePath);
FileSystemAccessRule rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow);
fSecurity.SetAccessRule(rule);
File.SetAccessControl(filePath, fSecurity);
}
A good solution is to grant full control to Everyone using xcacls.exe or any other ACL tool. This tool can be added as a custom action in your setup project.
Granting privileges to each user is not recommended because future accounts will not be covered. Also, doing this through custom code doesn't always work. Windows permissions are a bit tricky when it comes to controlling them through code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With