Permissão de gravação em pasta

string sPath    = Path.GetDirectoryName(Application.ExecutablePath);
string sTmpPath = sPath + "Temp";

// ********* REMOVER *************
//MessageBox.Show("Path: " + sTmpPath, "Tz0 info", MessageBoxButtons.OK, MessageBoxIcon.Information);

if (!Directory.Exists(sTmpPath))
Directory.CreateDirectory(sTmpPath);

// Pega a segurança atual da pasta
DirectorySecurity oDirSec = Directory.GetAccessControl(sTmpPath);

// Define o usuário Everyone (Todos)
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
//SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
NTAccount oAccount = sid.Translate(typeof(NTAccount)) as NTAccount;

oDirSec.PurgeAccessRules(oAccount);

FileSystemAccessRule fsAR = new FileSystemAccessRule(oAccount,
FileSystemRights.Modify,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.None,
AccessControlType.Allow);

// Atribui a regra de acesso alterada
oDirSec.SetAccessRule(fsAR);
Directory.SetAccessControl(sTmpPath, oDirSec);

source

Leave a Reply