Forked from richardschoen/gist:78ed5bd3b0656ba8eb4adfff9715e811
Created
June 1, 2021 08:46
-
-
Save PurwantoGZ/7a21bbc1c1e775a2d82538c09ae54b20 to your computer and use it in GitHub Desktop.
C# - set directory permissions for Everyone to Full Control. Useful when you need to store settings and other files in your app directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Security.Principal; | |
using System.Security.AccessControl; | |
using System.IO; | |
namespace RSSetDirPermissionsCS | |
{ | |
public class RsDirPermissions | |
{ | |
string _lastError = ""; | |
/// <summary> | |
/// Set Everyone Full Control permissions for selected directory | |
/// </summary> | |
/// <param name="dirName"></param> | |
/// <returns></returns> | |
bool SetEveryoneAccess(string dirName) | |
{ | |
try | |
{ | |
// Make sure directory exists | |
if (Directory.Exists(dirName) == false) | |
throw new Exception(string.Format("Directory {0} does not exist, so permissions cannot be set.", dirName)); | |
// Get directory access info | |
DirectoryInfo dinfo = new DirectoryInfo(dirName); | |
DirectorySecurity dSecurity = dinfo.GetAccessControl(); | |
// Add the FileSystemAccessRule to the security settings. | |
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)); | |
// Set the access control | |
dinfo.SetAccessControl(dSecurity); | |
_lastError = String.Format("Everyone FullControl Permissions were set for directory {0}", dirName)); | |
return true; | |
} catch (Exception ex) | |
{ | |
_lastError = ex.Message; | |
return false; | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment