использую такой код
string dir = @"\\remote_comp\dirpath";
DirectoryInfo dInfo = new DirectoryInfo(dir);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
SecurityIdentifier si = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
IdentityReference ir = si.Translate(typeof(NTAccount));
FileSystemAccessRule ar = new FileSystemAccessRule(ir, FileSystemRights.Modify, AccessControlType.Allow);
dSecurity.AddAccessRule(ar);
dInfo.SetAccessControl(dSecurity);
в результате группа "все" добавляется, но из разрешений для нее стоит только галочка "особые разрешения" (серая, т.е. унаследованная)
все остальные чекбоксы белые, т.е. наследования нет, просто не установлены
что делаю не так ?
Здравствуйте, Аноним, Вы писали:
А>использую такой код
А>А> string dir = @"\\remote_comp\dirpath";
А> DirectoryInfo dInfo = new DirectoryInfo(dir);
А> DirectorySecurity dSecurity = dInfo.GetAccessControl();
А> SecurityIdentifier si = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
А> IdentityReference ir = si.Translate(typeof(NTAccount));
А> FileSystemAccessRule ar = new FileSystemAccessRule(ir, FileSystemRights.Modify, AccessControlType.Allow);
А> dSecurity.AddAccessRule(ar);
А> dInfo.SetAccessControl(dSecurity);
А>
А>в результате группа "все" добавляется, но из разрешений для нее стоит только галочка "особые разрешения" (серая, т.е. унаследованная)
А>все остальные чекбоксы белые, т.е. наследования нет, просто не установлены
А>что делаю не так ?
Попробуйте (FileSystemRights.Read | FileSystemRights.Write) или FileSystemRights.FullControl вместе Modify. Галочки скорей всего поставяться.
Здравствуйте, KonstSK, Вы писали:
KSK>Здравствуйте, Аноним, Вы писали:
А>>использую такой код
А>>А>> string dir = @"\\remote_comp\dirpath";
А>> DirectoryInfo dInfo = new DirectoryInfo(dir);
А>> DirectorySecurity dSecurity = dInfo.GetAccessControl();
А>> SecurityIdentifier si = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
А>> IdentityReference ir = si.Translate(typeof(NTAccount));
А>> FileSystemAccessRule ar = new FileSystemAccessRule(ir, FileSystemRights.Modify, AccessControlType.Allow);
А>> dSecurity.AddAccessRule(ar);
А>> dInfo.SetAccessControl(dSecurity);
А>>
А>>в результате группа "все" добавляется, но из разрешений для нее стоит только галочка "особые разрешения" (серая, т.е. унаследованная)
А>>все остальные чекбоксы белые, т.е. наследования нет, просто не установлены
А>>что делаю не так ?
KSK>Попробуйте (FileSystemRights.Read | FileSystemRights.Write) или FileSystemRights.FullControl вместе Modify. Галочки скорей всего поставяться.
я эти все варианты пробовал, и на разных компах результат тот же.
даже на винапи переписал и все равно тоже самое
А>я эти все варианты пробовал, и на разных компах результат тот же.
А>даже на винапи переписал и все равно тоже самое
Я с помощью WMI, расшаривал папку на удаленной машине и менял права доступа к расшареной папке. Были те же проблемы с галочками и особым разрешением.
Заменил енумы на следущие значения констант:
private const uint ACE_FULL_CONTROL = 2032127;
private const uint ACE_READ = 1179817;
private const uint ACE_MODIFY = 1245631;
Могу написать пример, если это имено то что вам нужно. Код будет конечно сложнее, и уверен что можно все сделать и с помощью FileSystemAccessRule
Здравствуйте, KonstSK, Вы писали:
А>>я эти все варианты пробовал, и на разных компах результат тот же.
А>>даже на винапи переписал и все равно тоже самое
KSK>Я с помощью WMI, расшаривал папку на удаленной машине и менял права доступа к расшареной папке. Были те же проблемы с галочками и особым разрешением.
KSK>Заменил енумы на следущие значения констант:
KSK>KSK> private const uint ACE_FULL_CONTROL = 2032127;
KSK> private const uint ACE_READ = 1179817;
KSK> private const uint ACE_MODIFY = 1245631;
KSK>
KSK>Могу написать пример, если это имено то что вам нужно. Код будет конечно сложнее, и уверен что можно все сделать и с помощью FileSystemAccessRule
спасибо, напишите пожалуйста
кстати, если смотреть разрешения через cacls то показывает, что установлен полный доступ, и реальные разрешения похоже устанавливаются, так как запись в папку происходит
похоже, что глюки с отображенгием в графическом интерфейсе. причем смотрел и на висте и на хр
А>спасибо, напишите пожалуйста
тысяча извинений, я как-то не уследил за ответом, ушел в отпуск и забыл
Если все еще вопрос открыт, вот пример (hostName = "localhost"):
private const uint ACE_FULL_CONTROL = 2032127;
private const uint ACE_READ = 1179817;
private const uint ACE_MODIFY = 1245631;
private const uint ACE_FLAG_INHERITED = 3;
private const uint ACE_TYPE_ACCESS_ALLOWED = 0;
public void CreateShareFolder (string hostName, string localFolderPath, string shareName)
{
try
{
ConnectionOptions connectionOptions = createConnectionOptions();
string managementPath = String.Format(@"\\{0}\root\cimv2", hostName);
ManagementScope scope =
new ManagementScope(managementPath, connectionOptions);
using (ManagementClass processClass = new ManagementClass(scope,
new ManagementPath("Win32_Process"), new ObjectGetOptions()))
{
processClass.InvokeMethod("Create",
new object[] {String.Format("cmd.exe /c mkdir {0}", localFolderPath)});
}
using (ManagementClass shareClass = new ManagementClass(scope,
new ManagementPath("Win32_Share"),
new ObjectGetOptions()))
{
using (ManagementObject sd = createSecurityDescriptor(scope))
{
using (ManagementBaseObject parameters = shareClass.GetMethodParameters("Create"))
{
parameters ["Description"] = shareName;
parameters ["Name"] = shareName;
parameters ["Path"] = localFolderPath;
parameters ["Type"] = 0x0;
parameters ["Access"] = sd;
using (ManagementBaseObject result = shareClass.InvokeMethod("Create", parameters, null))
{
// Check to see if the method invocation was successful
uint errorCode = ((uint) result.Properties ["ReturnValue"].Value);
if (errorCode != SystemErrorCode.ERROR_SUCCESS)
{
throw new Exception("Failed to share folder...");
}
}
}
}
}
}
catch (Exception ex) {...}
}
public void ChangeSharePermissions (string hostName, string shareName)
{
try
{
ConnectionOptions connectionOptions = createConnectionOptions();
ManagementScope scope =
new ManagementScope(String.Format(@"\\{0}\root\cimv2", hostName), connectionOptions);
using (ManagementObject shareSecuritySetting = new ManagementObject(scope,
new ManagementPath("Win32_LogicalShareSecuritySetting.Name='GIMInbox'"), new ObjectGetOptions()))
{
using (ManagementObject sd = createSecurityDescriptor(scope))
{
using (ManagementBaseObject inParams =
shareSecuritySetting.GetMethodParameters("SetSecurityDescriptor"))
{
inParams.Properties ["Descriptor"].Value = sd;
using (ManagementBaseObject result = shareSecuritySetting.InvokeMethod("SetSecurityDescriptor", inParams, null))
{
// Check to see if the method invocation was successful
uint errorCode = ((uint) result.Properties ["ReturnValue"].Value);
if (errorCode != SystemErrorCode.ERROR_SUCCESS)
{
throw new Exception("Failed to set permissions...");
}
}
}
}
}
}
catch (Exception ex){...}
}
private ConnectionOptions createConnectionOptions()
{
ConnectionOptions connectionOptions = new ConnectionOptions();
// для localhost слудущие 2 строчки не нужны
//connectionOptions.Username = {UserName};
//connectionOptions.Password = {Password };
return connectionOptions;
}
private ManagementObject createSecurityDescriptor (ManagementScope scope)
{
ManagementClass sdClass = new ManagementClass(scope,
new ManagementPath("Win32_SecurityDescriptor"), new ObjectGetOptions());
ManagementObject sd = sdClass.CreateInstance();
ManagementClass trusteeClass = new ManagementClass(scope,
new ManagementPath("Win32_Trustee"), new ObjectGetOptions());
ManagementObject trustee = trusteeClass.CreateInstance();
ManagementObject everyoneTrustee = trusteeClass.CreateInstance();
ManagementClass aceClass = new ManagementClass(scope,
new ManagementPath("Win32_ACE"), new ObjectGetOptions());
ManagementObject ace = aceClass.CreateInstance();
ManagementObject everyoneAce = aceClass.CreateInstance();
sd.Properties ["ControlFlags"].Value = 4;
trustee.Properties ["Domain"].Value = UserLoginInfo.Current.UserDomain;
trustee.Properties ["Name"].Value = UserLoginInfo.Current.UserName;
trustee.Properties ["SID"].Value = getSIDBinaryRepresentation(scope);
ace.Properties ["AccessMask"].Value = ACE_FULL_CONTROL;
ace.Properties ["AceFlags"].Value = ACE_FLAG_INHERITED;
ace.Properties ["AceType"].Value = ACE_TYPE_ACCESS_ALLOWED;
ace.Properties ["Trustee"].Value = trustee;
// everyone has the same SID on each host
NTAccount ntAccount = new NTAccount("Everyone");
SecurityIdentifier sid = (SecurityIdentifier) ntAccount.Translate(typeof(SecurityIdentifier));
byte [] sidArray = new byte [sid.BinaryLength];
sid.GetBinaryForm(sidArray, 0);
everyoneTrustee.Properties ["SID"].Value = sidArray;
everyoneAce.Properties ["AccessMask"].Value = ACE_READ;
everyoneAce.Properties ["AceFlags"].Value = ACE_FLAG_INHERITED;
everyoneAce.Properties ["AceType"].Value = ACE_TYPE_ACCESS_ALLOWED;
everyoneAce.Properties ["Trustee"].Value = everyoneTrustee;
ArrayList arr = new ArrayList();
arr.Add(ace);
arr.Add(everyoneAce);
sd ["DACL"] = arr.ToArray();
return sd;
}
private object getSIDBinaryRepresentation (ManagementScope scope)
{
using (ManagementObject account = new ManagementObject(scope,
new ManagementPath("Win32_Account.Name='" + {UserName} + "',Domain='" + {UserDomain} + "'"), new ObjectGetOptions()))
{
using (ManagementObject accountSID = new ManagementObject(scope,
new ManagementPath("Win32_SID.SID='" + account.Properties ["SID"].Value + "'"), new ObjectGetOptions()))
{
return accountSID.Properties ["BinaryRepresentation"].Value;
}
}
}