/// <summary>
/// Sets security permissions for all files in a directory.
/// </summary>
public static void SetDirectoryFilesAccess(string directory, SecurityIdentifier sid, FileSystemRights rights, AccessControlType type)
{
try
{
// first we will attempt to take ownership of the file
// this ensures (if successful) that all users can change security
// permissions for the file without admin access
ProcessStartInfo si = new ProcessStartInfo("cmd.exe");
si.RedirectStandardInput = false;
si.RedirectStandardOutput = false;
si.RedirectStandardError = false;
si.UseShellExecute = false;
si.Arguments = string.Format("/c takeown /f \"{0}\" /r /d y", directory);
si.CreateNoWindow = true;
si.WindowStyle = ProcessWindowStyle.Hidden;
if (Utilities.IsMonoRunning())
{
si.FileName = "chown";
si.Arguments = string.Format("-R $USER:$USER \"{0}\"", directory);
}
Process process = Process.Start(si);
bool result = (process != null);
if (result)
{
process.EnableRaisingEvents = true;
process.WaitForExit();
if (process.ExitCode != 0)
{
return;
}
process.Close();
// after successfully gaining ownership, parse each file in the
// directory (recursively) and update its access rights
foreach (string filename in Utilities.GetDirectoryFileList(directory, "*", SearchOption.AllDirectories))
{
Utilities.SetFileAccess(filename, sid, rights, type);
}
}
}
catch (UnauthorizedAccessException)
{
}
}