Skip to content

Instantly share code, notes, and snippets.

@richardschoen
Created November 1, 2018 12:20
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save richardschoen/78ed5bd3b0656ba8eb4adfff9715e811 to your computer and use it in GitHub Desktop.
Save richardschoen/78ed5bd3b0656ba8eb4adfff9715e811 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
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;
}
}
}
}
@volehuy1998
Copy link

Thank you. I will tried.

@volehuy1998
Copy link

Thank you for your code, I tested and it worked very well. I have a small problem, folowing microsoft document, it support only on Windows platform. Except "command line", does we have any solution for Linux?

@richardschoen
Copy link
Author

In Linux I'm guessing you would need to use chmod or something else to set appropriate file and directory authorities. You should be able to execute chmod from .Net in Linux.

@volehuy1998
Copy link

It's good information for me. Thank you @richardschoen !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment