Inheritance: FileSystemSecurity
Exemplo n.º 1
9
        /// <summary>
        /// Initializes a new instance of the <see cref="FileSystem" /> class.
        /// </summary>
        /// <param name="root">The absolute path to the root directory of this file system (..../Pie/ or .../Pie).</param>
        public FileSystem(String root)
        {
            // Append separator to root, if it hasn't got it
            _fileSystemRoot = root + (root.EndsWith(PathSeparator) ? String.Empty : PathSeparator);

            DirectoryInfo dirInfo = new DirectoryInfo(_fileSystemRoot);

            // Create directory if it doesn't exist
            if (!Directory.Exists(_fileSystemRoot))
            {
                Directory.CreateDirectory(_fileSystemRoot);
            }

            // Make sure the directory has the right permissions
            try
            {
                // Attempt to get a list of security permissions from the folder.
                // This will raise an exception if the path is read only or do not have access to view the permissions.
                System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(_fileSystemRoot);
            }
            catch (UnauthorizedAccessException)
            {
                var security = new DirectorySecurity();
                var windowsIdentity = WindowsIdentity.GetCurrent();
                if (windowsIdentity != null)
                {
                    var id = windowsIdentity.User;
                    var rule = new FileSystemAccessRule(id, FileSystemRights.FullControl, AccessControlType.Allow);
                    security.AddAccessRule(rule);
                    dirInfo.SetAccessControl(security);
                }
            }
        }
Exemplo n.º 2
1
        /// <summary>
        /// Make a folder if doesn't exist
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static bool MakeFolder(string folderPath)
        {
            if (!Directory.Exists(folderPath))
            {
                try
                {
                    DirectorySecurity securityRules = new DirectorySecurity();
                    securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl,
                                                                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                            PropagationFlags.NoPropagateInherit,
                                                                            AccessControlType.Allow));

                    Directory.CreateDirectory(folderPath, securityRules);
                    File.SetAttributes(folderPath, FileAttributes.Normal);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception trying to create folder: " + folderPath);
                    if (ex.InnerException != null)
                        Console.WriteLine(ex.InnerException.Message);
                    else
                        Console.WriteLine(ex.Message);
                    return false;
                }
            }
            return true;
        }
        public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path.Length == 0)
            {
                throw new ArgumentException(Properties.Resources.PATH_CANNOT_BE_THE_EMPTY_STRING_OR_ALL_WHITESPACE, "path");
            }

            if (mockFileDataAccessor.FileExists(path))
            {
                var message = string.Format(CultureInfo.InvariantCulture, @"Cannot create ""{0}"" because a file or directory with the same name already exists.", path);
                var ex = new IOException(message);
                ex.Data.Add("Path", path);
                throw ex;
            }

            path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path));

            if (!Exists(path))
            {
                mockFileDataAccessor.AddDirectory(path);
            }

            var created = new MockDirectoryInfo(mockFileDataAccessor, path);
            return created;
        }
Exemplo n.º 4
0
        static void SetAccessRule(string directory)
        {
            System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(directory);
            FileSystemAccessRule accRule = new FileSystemAccessRule(Environment.UserDomainName + "\\" + Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);

            sec.AddAccessRule(accRule);
        }
Exemplo n.º 5
0
    static int GetAccessControl(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                string arg0 = ToLua.CheckString(L, 1);
                System.Security.AccessControl.DirectorySecurity o = System.IO.Directory.GetAccessControl(arg0);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else if (count == 2)
            {
                string arg0 = ToLua.CheckString(L, 1);
                System.Security.AccessControl.AccessControlSections arg1 = (System.Security.AccessControl.AccessControlSections)ToLua.CheckObject(L, 2, typeof(System.Security.AccessControl.AccessControlSections));
                System.Security.AccessControl.DirectorySecurity     o    = System.IO.Directory.GetAccessControl(arg0, arg1);
                ToLua.PushSealed(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: System.IO.Directory.GetAccessControl"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
            private RawSecurityDescriptor CreateSecurityDescriptor(IEnumerable<IdentityRights> allowRights,
                IEnumerable<IdentityRights> denyRights = null)
            {
                var security = new DirectorySecurity();
                security.SetOwner(CurrentIdentity);
                security.SetGroup(Group);

                if (allowRights == null)
                    allowRights = Enumerable.Empty<IdentityRights>();

                if (denyRights == null)
                    denyRights = Enumerable.Empty<IdentityRights>();

                foreach (var right in allowRights)
                {
                    security.AddAccessRule(new FileSystemAccessRule(right.Identity, right.Rights,
                        AccessControlType.Allow));
                }

                foreach (var right in denyRights)
                {
                    security.AddAccessRule(new FileSystemAccessRule(right.Identity, right.Rights, AccessControlType.Deny));
                }

                var binaryDescriptor = security.GetSecurityDescriptorBinaryForm();
                return new RawSecurityDescriptor(binaryDescriptor, 0);
            }
Exemplo n.º 7
0
 /// <summary>
 ///为文件夹添加users,everyone用户组的完全控制权限
 /// </summary>
 /// <param name="dirPath"></param>
 public static void AddSecurityControll2Folder(string dirPath)
 {
     try
     {
         //获取文件夹信息
         DirectoryInfo dir = new DirectoryInfo(dirPath);
         //获得该文件夹的所有访问权限
         System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
         //设定文件ACL继承
         InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
         //添加ereryone用户组的访问权限规则 完全控制权限
         FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
         //添加Users用户组的访问权限规则 完全控制权限
         FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
         bool isModified = false;
         dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
         dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
         //设置访问权限
         dir.SetAccessControl(dirSecurity);
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         Console.WriteLine("AddSecurityControll2Folder is executed.");
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// 文件/文件夹权限修改
        /// </summary>
        /// <param name="fileSystemAccessRule">传入修改权限对象</param>
        /// <param name="path">路径</param>
        /// <param name="ifisFolder">是否为文件夹</param>
        public static void setAtrribute(FileSystemAccessRule fileSystemAccessRule, string path, int ifisFolder)
        {
            if (ifisFolder == 0)
            {
                FileInfo fileInfo = new FileInfo(path);
                //获得该文件的访问权限
                System.Security.AccessControl.FileSecurity fileSecurity = fileInfo.GetAccessControl();
                //添加ereryone用户组的访问权限规则 完全控制权限
                fileSecurity.AddAccessRule(fileSystemAccessRule);
                //设置访问权限
                fileInfo.SetAccessControl(fileSecurity);
            }
            else
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                //获得该文件夹的所有访问权限
                System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);

                //添加ereryone用户组的访问权限规则 完全控制权限
                FileSystemAccessRule everyoneFileSystemAccessRule = fileSystemAccessRule;
                bool isModified = false;
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
                //设置访问权限
                dir.SetAccessControl(dirSecurity);
            }
        }
Exemplo n.º 9
0
        private static void SetAcl(string path, SearchResult user, FileSystemRights right)
        {
            var userId = user.Properties["userPrincipalName"][0].ToString();
            var fullUserName = user.Properties["name"][0].ToString();
            var fullPath = path + fullUserName;
            var dir = new DirectoryInfo(fullPath);
            var ds = new DirectorySecurity();
            ds.SetAccessRuleProtection(true, false);

            var uacl = new FileSystemAccessRule(userId,
                right,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(uacl);

            var domainAdmins = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, AppSettings.GeneralSettings.DomainSid);
            var pacl = new FileSystemAccessRule(domainAdmins,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(pacl);

            var system = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);
            var sacl = new FileSystemAccessRule(system,
                FileSystemRights.FullControl,
                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                PropagationFlags.None,
                AccessControlType.Allow);
            ds.AddAccessRule(sacl);

            dir.SetAccessControl(ds);
        }
Exemplo n.º 10
0
		public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity)
		{
			if (directoryInfo == null)
				throw new ArgumentNullException (nameof (directoryInfo));

			directoryInfo.SetAccessControl (directorySecurity);
		}
Exemplo n.º 11
0
        static void Main(string[] args)
        {
            DirectorySecurity ds = new DirectorySecurity(@"C:\Program Files", AccessControlSections.Access);
            AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(NTAccount));

            Console.WriteLine("Identity Reference".PadRight(28)+ ": " + 
                    "Access Control Type".PadRight(20) + " " + "File System Rights");
            foreach (FileSystemAccessRule fsar in arc)
            {
                Console.WriteLine(fsar.IdentityReference.ToString().PadRight(28) + ": " + 
                    fsar.AccessControlType.ToString().PadRight(20) + " " + fsar.FileSystemRights);
            }

            Console.WriteLine();

            RegistrySecurity rs = Registry.LocalMachine.GetAccessControl();
            arc = rs.GetAccessRules(true, true, typeof(NTAccount));

            Console.WriteLine("Identity Reference".PadRight(28) + ": " +
                    "Access Control Type".PadRight(20) + " " + "Registry Rights");
            foreach (RegistryAccessRule rar in arc)
            {
                Console.WriteLine(rar.IdentityReference.ToString().PadRight(28) + ": " +
                    rar.AccessControlType.ToString().PadRight(20) + " " + rar.RegistryRights);
            }
        }
        public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            if (path.Length == 0)
            {
                throw new ArgumentException("Path cannot be the empty string or all whitespace.", "path");
            }

            if (mockFileDataAccessor.FileExists(path))
            {
                var message = string.Format(CultureInfo.InvariantCulture, @"Cannot create ""{0}"" because a file or directory with the same name already exists.", path);
                var ex = new IOException(message);
                ex.Data.Add("Path", path);
                throw ex;
            }

            path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path));

            if (!Exists(path))
            {
                mockFileDataAccessor.AddDirectory(path);
            }

            var created = new MockDirectoryInfo(mockFileDataAccessor, path);
            return created;
        }
Exemplo n.º 13
0
 public static void AddDirectorySecurity(string strPath, string Account, System.Security.AccessControl.FileSystemRights Rights, System.Security.AccessControl.AccessControlType ControlType)
 {
     System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(strPath);
     System.Security.AccessControl.DirectorySecurity accessControl = directoryInfo.GetAccessControl();
     accessControl.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(Account, Rights, ControlType));
     directoryInfo.SetAccessControl(accessControl);
 }
        public static void Copy(string source, string destination, bool copySubDirs, DirectorySecurity security)
        {
            var dir = new DirectoryInfo(source);
            var dirs = dir.GetDirectories();

            if (!dir.Exists)
            {
                throw new DirectoryNotFoundException(
                    "Source directory does not exist or could not be found: "
                    + source);
            }

            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination, security);
            }

            var files = dir.GetFiles();
            foreach (var file in files)
            {
                var temppath = Path.Combine(destination, file.Name);
                file.CopyTo(temppath, false);
            }

            if (!copySubDirs)
                return;

            foreach (var subdir in dirs)
            {
                var temppath = Path.Combine(destination, subdir.Name);
                Copy(subdir.FullName, temppath, true);
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Set required permissions to the Phalanger install folder. To enable phalanger ASP.NET app i.e. to generate/modify dynamic wrappers.
 /// </summary>
 /// <param name="folder">Phalanger install folder.</param>
 private static void SetEveryonePermission(string folder)
 {
     var everyonesid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     FileSystemAccessRule everyOne = new FileSystemAccessRule(everyonesid, FileSystemRights.FullControl | FileSystemRights.Write | FileSystemRights.Read, AccessControlType.Allow);
     DirectorySecurity dirSecurity = new DirectorySecurity(folder, AccessControlSections.Group);
     dirSecurity.AddAccessRule(everyOne);
     Directory.SetAccessControl(folder, dirSecurity);
 }
 public DirectoryAccessDenier(DirectoryInfo directory, FileSystemRights rights)
 {
     this.directory = directory;
     this.access = this.directory.GetAccessControl();
     this.denial = new FileSystemAccessRule(WindowsIdentity.GetCurrent().Name, rights, AccessControlType.Deny);
     this.access.AddAccessRule(this.denial);
     this.directory.SetAccessControl(this.access);
 }
Exemplo n.º 17
0
        private void show_Click(object sender, EventArgs e)
        {
            Thread showThread = new Thread((ThreadStart)(delegate()
            {
                string targetFolder = ".\\" + textBox1.Text;
                string desktoppath = targetFolder + "\\" + "desktop.ini";
                string wzh = @".\回收站.{645ff040-5081-101b-9f08-00aa002f954e}";
                string user = "******";
                string pw = @".\回收站.{645ff040-5081-101b-9f08-00aa002f954e}\astSetting.ini";
                string pw2 = targetFolder + "\\" + "astSetting.ini";
                var key = "=9bn&2g=4By3^GrCsP;oVQat/*6o%l#R"; //定义使用的密匙
                var jmh = Encrypt(key, textBox1.Text);        //加密textBox1的文本
                if (File.Exists(pw) && Directory.Exists(wzh))
                {
                    StreamReader rpw = new StreamReader(pw);
                    var tv = rpw.ReadLine();
                    rpw.Close();
                    if (tv == jmh)
                    {
                        try
                        {
                            label1.Text = "程序执行中,请稍后......\r\n执行过程中请不要操作本程序以及强制停止本程序!\r\n花费的时间和文件数量成正比,零散文件越多,花费时间将会越长。";
                            DirectoryInfo hf = new DirectoryInfo(wzh);
                            hf.MoveTo(targetFolder);                                        //重命名文件夹,恢复源文件夹
                            File.SetAttributes(targetFolder, FileAttributes.Normal);        //恢复文件夹访问权限
                            System.Security.AccessControl.DirectorySecurity tf;
                            tf = new System.Security.AccessControl.DirectorySecurity();
                            tf.RemoveAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Deny));
                            System.IO.Directory.SetAccessControl(targetFolder, tf);
                            File.Delete(pw2);
                            File.Delete(desktoppath);
                            MessageBox.Show("显示成功!", "恭喜!");
                            label1.Text = "友情提示:\r\n小撸怡情,大撸伤身,强撸灰飞烟灭,猛撸惊天动地。";
                        }
                        catch
                        {
                            MessageBox.Show("发生几率极低的未知错误,显示无法正常执行!", "注意!");
                        }
                    }
                    else
                    {
                        MessageBox.Show("你输入的指令有误!", "出错啦!");
                        label1.Text = "显示失败!\r\n如无法自行解决,可以联系本程序作者Chias(www.chias.me)解决。";
                    }
                }
                else if (textBox1.Text == "")
                {
                    label1.Text = "你妹!能随便操..弄的吗?!";
                }
                else
                {
                    MessageBox.Show("你妹!能随便操..弄的吗?!", "警告!");
                    label1.Text = "你妹!叫你乱操..弄!这下爽了吧!\r\n这件事告诉我们一个道理:\r\n酒后可以乱伦乱性,但“密码”却是不能乱改乱记的。";
                }
            }));

            showThread.Start();
        }
Exemplo n.º 18
0
        public static void SetAccessControl(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity)
        {
            if (directorySecurity == null)
                throw new ArgumentNullException(nameof(directorySecurity));
            Contract.EndContractBlock();

            String fullPath = Path.GetFullPath(directoryInfo.FullName);
            directorySecurity.Persist(fullPath);
        }
Exemplo n.º 19
0
        /// <summary>
        /// 作用:文件夹授权
        /// 作者:杨洋AY
        /// 添加时间:2016-6-19
        /// </summary>
        /// <param name="DirectoryPath">需要被授权的文件夹,默认是Everyone</param>
        public virtual void AccessDirectoryRights(string DirectoryPath, string DirectoryAuth = "Everyone")
        {
            DirectoryInfo di = Directory.CreateDirectory(DirectoryPath);

            //赋予文件夹权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = di.GetAccessControl();
            dirSecurity.AddAccessRule(new FileSystemAccessRule(DirectoryAuth, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
            di.SetAccessControl(dirSecurity);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Add an access rule to a folder
        /// </summary>
        ///
        /// <param name="Path">Folder path</param>
        /// <param name="User">UNC path to user profile ex. Environment.UserDomainName + "\\" + Environment.UserName</param>
        /// <param name="Rights">Desired file system rights</param>
        /// <param name="Access">Desired level of access</param>
        public static void AddAccessRule(string Path, string User, FileSystemRights Rights, AccessControlType Access)
        {
            // Get a DirectorySecurity object that represents the current security settings
            System.Security.AccessControl.DirectorySecurity sec = System.IO.Directory.GetAccessControl(Path);
            // Add the FileSystemAccessRule to the security settings
            FileSystemAccessRule accRule = new FileSystemAccessRule(User, Rights, Access);

            sec.AddAccessRule(accRule);
        }
Exemplo n.º 21
0
        protected override void ExecuteOnDir(DirectoryInfo dir)
        {
            DirectorySecurity dirSec = new DirectorySecurity(dir.FullName, AccessControlSections.Access);

            Log(Level.Info, Resources.AddAccessRuleAdding, Rights, NTAccount, dir.FullName);
            FileSystemAccessRule newRule = new FileSystemAccessRule(new NTAccount(NTAccount), Rights, InheritanceFlags, PropagationFlags, AccessControlType);
            dirSec.AddAccessRule(newRule);
            dir.SetAccessControl(dirSec);
        }
Exemplo n.º 22
0
 private static bool hasWriteAccessToFolder(string path)
 {
     try {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(path);
         return(true);
     } catch (UnauthorizedAccessException) {
         return(false);
     }
 }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            DirectorySecurity ds = new DirectorySecurity();
            ds.AddAccessRule(new FileSystemAccessRule("Guest", FileSystemRights.Read, AccessControlType.Allow));
            string newFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Guest");
            Directory.CreateDirectory(newFolder, ds);

            string newFile = System.IO.Path.Combine(newFolder, "Data.dat");
            File.Create(newFile);
        }
Exemplo n.º 24
0
 public Form1()
 {
     InitializeComponent();
     orgHieght = this.Height;
     bigHeight = this.orgHieght + this.richTextBox1.Height + 10;
     d = new DirectorySecurity();
     fr = new FileSystemAccessRule(Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow);
     d.AddAccessRule(fr);
     mainDir = Directory.CreateDirectory("c:/JTRacker", d);
 }
Exemplo n.º 25
0
 private void butOK_Click(object sender, System.EventArgs e)
 {
     if(!Directory.Exists(textLocation.Text)){
         MsgBox.Show(this,"Location does not exist.");
         return;
     }
     if(Directory.Exists(ODFileUtils.CombinePaths(textLocation.Text,textName.Text))) {
         MsgBox.Show(this,"Folder already exists.");
         return;
     }
     try {
         FileSystemAccessRule fsar=new FileSystemAccessRule("everyone",FileSystemRights.FullControl,AccessControlType.Allow);
         DirectorySecurity ds=new DirectorySecurity();
         ds.AddAccessRule(fsar);
         string requestDir=textLocation.Text;
         string rootFolderName=textName.Text;
         string rootDir=ODFileUtils.CombinePaths(requestDir,rootFolderName);
         //Enable file sharing for the A to Z folder.
         if(Environment.OSVersion.Platform==PlatformID.Unix) {
             //Process.Start("net","usershare add OpenDentImages \""+rootDir+"\"");//for future use.
         }
         else {//Windows
             Process.Start("NET","SHARE OpenDentImages=\""+rootDir+"\"");
         }
         //All folder names to be created should be put in this list, so that each folder is created exactly
         //the same way.
         string[] aToZFolderNames=new string[] {
             "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
             "O","P","Q","R","S","T","U","V","W","X","Y","Z",
             "EmailAttachments","Forms","Reports","Sounds",
         };
         //Create A to Z folders in root folder.
         for(int i=0;i<aToZFolderNames.Length;i++) {
             string pathToCreate=ODFileUtils.CombinePaths(rootDir,aToZFolderNames[i]);
             if(!Directory.Exists(pathToCreate)) {
                 // Mono does support Directory.CreateDirectory(string, DirectorySecurity)
     #if !LINUX
                 Directory.CreateDirectory(pathToCreate,ds);
     #else
                 Directory.CreateDirectory(pathToCreate);
     #endif
             }
         }
         //Save new image path into the DocPath and
         //set "use A to Z folders" check-box to checked.
         Prefs.UpdateString(PrefName.DocPath,rootDir);
         Prefs.UpdateString(PrefName.AtoZfolderNotRequired,"0");
         Cache.Refresh(InvalidType.Prefs);
         //Prefs_client.RefreshClient();
     }
     catch(Exception ex) {
         Logger.openlog.LogMB("Failed to create A to Z folders: "+ex.ToString(),Logger.Severity.ERROR);
     }
     DialogResult=DialogResult.OK;
 }
Exemplo n.º 26
0
        internal static void CreateDirectory(string path, IsolatedStorageScope scope)
        {
            if (Directory.Exists(path))
                return;

            DirectoryInfo info = Directory.CreateDirectory(path);

            if (IsMachine(scope) && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // Need to emulate COMIsolatedStorage::CreateDirectoryWithDacl(), which gives the following rights:
                //
                //  World / Everyone (S-1-1-0 / SECURITY_WORLD_RID) -> (FILE_GENERIC_WRITE | FILE_GENERIC_READ) & (~WRITE_DAC)
                //  Creator Owner (S-1-3-0 / SECURITY_CREATOR_OWNER_RID) -> FILE_ALL_ACCESS
                //  Local Admins (S-1-5-32 / SECURITY_BUILTIN_DOMAIN_RID & DOMAIN_ALIAS_RID_ADMINS) -> FILE_ALL_ACCESS
                // 
                // When looking at rights through the GUI it looks like this:
                //
                //  "Everyone" -> Read, Write
                //  "Administrators" -> Full control
                //  "CREATOR OWNER" -> Full control
                //
                // With rights applying to "This folder, subfolders, and files". No inheritance from the parent folder.
                //
                // Note that trying to reset the rules for CREATOR OWNER leaves the current directory with the actual creator's SID.
                // (But applies CREATOR OWNER as expected for items and subdirectories.) Setting up front when creating the directory
                // doesn't exhibit this behavior, but as we can't currently do that we'll take the rough equivalent for now.

                DirectorySecurity security = new DirectorySecurity();

                // Don't inherit the existing rules
                security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false);
                security.AddAccessRule(new FileSystemAccessRule(
                    identity: new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                    fileSystemRights: FileSystemRights.Read | FileSystemRights.Write,
                    inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    propagationFlags: PropagationFlags.None,
                    type: AccessControlType.Allow));

                security.AddAccessRule(new FileSystemAccessRule(
                    identity: new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null),
                    fileSystemRights: FileSystemRights.FullControl,
                    inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    propagationFlags: PropagationFlags.None,
                    type: AccessControlType.Allow));

                security.AddAccessRule(new FileSystemAccessRule(
                    identity: new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, null),
                    fileSystemRights: FileSystemRights.FullControl,
                    inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    propagationFlags: PropagationFlags.None,
                    type: AccessControlType.Allow));

                info.SetAccessControl(security);
            }
        }
        static void Main(string[] args)
        {
            DirectorySecurity ds = new DirectorySecurity();
            ds.AddAccessRule(new FileSystemAccessRule("Rafa&Pri", FileSystemRights.Read, AccessControlType.Allow));
            string newFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Rafa&Pri");
            Directory.CreateDirectory(newFolder, ds);

            FileSecurity fs = new FileSecurity();
            fs.AddAccessRule(new FileSystemAccessRule("Rafa&Pri", FileSystemRights.FullControl, AccessControlType.Allow));
            string newFile = Path.Combine(newFolder, "Data.dat");
            File.Create(newFile, 100, FileOptions.None, fs);
        }
Exemplo n.º 28
0
 /// <summary>
 /// Função que verifica as permissões do usuário atual em um diretório específico, retornando como true se possuir permissões.
 /// </summary>
 /// <param name="Folder">Pasta a ser verificado as respectivas permissões.</param>
 public Boolean VerificaPermissaoPasta(String Folder)
 {
     try
     {
         System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(Folder);
         return(true);
     }
     catch (Exception ex)
     {
         throw new Exception(string.Format("Usuário não possui permissão na pasta '{0}'", Folder), ex);
     }
 }
        public override DirectoryInfoBase CreateDirectory(string path, DirectorySecurity directorySecurity)
        {
            path = EnsurePathEndsWithDirectorySeparator(mockFileDataAccessor.Path.GetFullPath(path));
            if (!Exists(path))
                mockFileDataAccessor.AddDirectory(path);
            var created = new MockDirectoryInfo(mockFileDataAccessor, path);

            var parent = GetParent(path);
            if (parent != null)
                CreateDirectory(GetParent(path).FullName, directorySecurity);

            return created;
        }
Exemplo n.º 30
0
        public void BreadcrumbsCreationDoesNotFailWhenAccessDenied()
        {
            var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            var directory = new DirectoryInfo(TempFolderPath);
            var security = new DirectorySecurity();
            security.AddAccessRule(new FileSystemAccessRule(userName, FileSystemRights.Write, AccessControlType.Deny));
            directory.SetAccessControl(security);

            var breadcrumbs = new Servicing.Breadcrumbs(TempFolderPath);
            breadcrumbs.CreateBreadcrumb("Test", new NuGet.SemanticVersion("1.0.0"));

            Assert.Empty(Directory.GetFiles(TempFolderPath));
        }
Exemplo n.º 31
0
 /// <summary>
 /// 创建文件夹
 /// </summary>
 /// <param name="path">必须是物理路径</param>
 public static void CreateFile(this string path)
 {
     if (!Directory.Exists(path))//如果不存在文件夹,则创建
     {
         try
         {
             Directory.CreateDirectory(path);
             DirectorySecurity security = new DirectorySecurity(path, AccessControlSections.Owner);
             SecurityIdentifier identifier = new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, null);
             security.SetAccessRule(new FileSystemAccessRule(identifier, FileSystemRights.FullControl, AccessControlType.Allow));
         }
         catch (FileNotFoundException e) { throw e; }
     }
 }
Exemplo n.º 32
0
        public void parseDir(String path)
        {
            foreach (String f in Directory.GetDirectories(path))
            {
                if (f.EndsWith(".svn"))
                {
                    DirectoryInfo dinfo;
                    try
                    {
                        DirectorySecurity ds = new DirectorySecurity(f, AccessControlSections.Access);
                        FileSystemAccessRule fsRule = new FileSystemAccessRule(self.Name,
                            FileSystemRights.FullControl,
                            AccessControlType.Allow);
                        ds.SetAccessRule(fsRule);

                        dinfo = new DirectoryInfo(f);
                        dinfo.Attributes = FileAttributes.Normal;
                        dinfo.SetAccessControl(ds);
                    }
                    catch (Exception err)
                    {
                    }

                    dinfo = new DirectoryInfo(f);
                    DirectorySecurity sec = dinfo.GetAccessControl();
                    sec.SetOwner(self.Owner);

                    setFileSecurity(f);

                    addListItem(f);
                    Application.DoEvents();

                    try
                    {
                        Directory.Delete(f, true);
                    }
                    catch (Exception err)
                    {
                        MessageBox.Show(err.Message);
                    }
                }
                else
                {
                    //addListItem(f);
                    Application.DoEvents();
                    parseDir(f);
                }
            }
        }
Exemplo n.º 33
0
 public static bool AllowFolderAccess(string path, FileSystemRights rights)
 {
     try
     {
         var security = new System.Security.AccessControl.DirectorySecurity();
         var usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
         security.AddAccessRule(new FileSystemAccessRule(usersSid, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
         Directory.SetAccessControl(path, security);
         return true;
     }
     catch
     {
         return false;
     }
 }
        static void Main()
        {
            const string dir = @"C:\test";

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(dir);
            ds.AddAccessRule(new FileSystemAccessRule("Guest", FileSystemRights.Read, AccessControlType.Allow));
            Directory.SetAccessControl(dir, ds);

            Console.WriteLine(ds.GetSecurityDescriptorSddlForm(AccessControlSections.All));
        }
Exemplo n.º 35
0
        /// <summary>
        /// checks if user has rights to acess the directory
        /// </summary>
        /// <param name="username">user's name</param>
        /// <param name="path">path of directory</param>
        /// <returns>true if can has right to acess directory false otherwise</returns>
        public Boolean UserHasAccessOnDirectory(string username, string path)
        {
            try
            {
                Boolean ap = false;
                //  System.Windows.Forms.MessageBox.Show("hi 2");
                WhiteTigerService.conf.ReadConfig();
                if (WhiteTigerService.pref.Filesecurity == true)
                {
                    if ((username != null) || (path != null) || (Directory.Exists(path) != false))
                    {
                        DirectoryInfo dirinf = new DirectoryInfo(path);

                        System.Security.AccessControl.DirectorySecurity ds = dirinf.GetAccessControl();
                        AuthorizationRuleCollection aucol = ds.GetAccessRules(true, true,
                                                                              typeof(System.Security.Principal.WindowsIdentity));
                        WindowsIdentity wi = new WindowsIdentity(username);
                        //  System.Windows.Forms.MessageBox.Show("hi 1");
                        for (int i = 0; i < aucol.Count; i++)
                        {
                            FileSystemAccessRule drsac = (FileSystemAccessRule)aucol[i];
                            WindowsPrincipal     pr    = new WindowsPrincipal(wi);

                            if ((wi.User.Equals(drsac.IdentityReference) == true) || (pr.IsInRole((SecurityIdentifier)drsac.IdentityReference) == true))
                            {
                                //System.Windows.Forms.MessageBox.Show(wi.User.Value + "\n" + drsac.IdentityReference.Value);

                                ap = true;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    // System.Windows.Forms.MessageBox.Show("hi ");
                    ap = true;
                }
                return(ap);
            }


            catch (Exception e)
            {
                program.errorreport(e);
                return(false);
            }
        }
 public static DirectoryInfo CreateDirectory(string path, DirectorySecurity directorySecurity)
 {
     if (path == null)
     {
         throw new ArgumentNullException("path");
     }
     if (path.Length == 0)
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
     }
     string fullPathInternal = Path.GetFullPathInternal(path);
     string demandDir = GetDemandDir(fullPathInternal, true);
     new FileIOPermission(FileIOPermissionAccess.Read, new string[] { demandDir }, false, false).Demand();
     InternalCreateDirectory(fullPathInternal, path, directorySecurity);
     return new DirectoryInfo(fullPathInternal, false);
 }
Exemplo n.º 37
0
        public static void CreateDirectory(string path)
        {
            if (!Directory.Exists(path))
            {
                DirectorySecurity securityRules = new DirectorySecurity();
                
               

                DirectoryInfo dir = Directory.CreateDirectory(path);
                dir.SetAccessControl(securityRules);
               
                
                //securityRules.AddAccessRule(new FileSystemAccessRule(@"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
                
            }
        }
Exemplo n.º 38
0
        private static void ReplaceAllChildPermissions(DirectoryInfo dirInfo, DirectorySecurity security)
        {
            dirInfo.SetAccessControl(security);

            foreach (var fi in dirInfo.GetFiles())
            {
                var fileSecurity = fi.GetAccessControl();
                fileSecurity.SetAccessRuleProtection(false, false);
                fi.SetAccessControl(fileSecurity);
            }

            foreach (var di in dirInfo.GetDirectories())
            {
                ReplaceAllChildPermissions(di, security);
            }
        }
        /// <summary>
        ///为文件夹添加users,IIS_IUSRS用户组的完全控制权限
        /// </summary>
        /// <param name="dirPath"></param>
        public static void AddSecurityControll2Folder(string dirPath, AuthorizedUsers user)
        {
            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(dirPath);

            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            //设定文件ACL继承
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //添加IIS_IUSRS用户组的访问权限规则 完全控制权限
            FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(EnumHelper.GetDescription(user), FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add, fileSystemAccessRule, out isModified);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }
Exemplo n.º 40
0
        public static void AddSharePermissionToFolder(string folderPath, string domain, string accountName)
        {
            DirectoryInfo dir          = new DirectoryInfo(folderPath);
            string        fullUserName = domain + "\\" + accountName;

            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //添加Users用户组的访问权限规则 完全控制权限
            //FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            FileSystemAccessRule userRule = new FileSystemAccessRule(fullUserName, FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add, userRule, out isModified);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }
Exemplo n.º 41
0
 /// <summary>
 /// Create a directory FullAcess
 /// </summary>
 /// <param name="path">directory path</param>
 /// <returns>True: create directory successfully. False: create directory failed</returns>
 public static bool CreateDirectoryFullAcess(string path)
 {
     try
     {
         if (Directory.Exists(path) == false) // not existing
         {
             var dirInfo = new DirectoryInfo(path);
             var dirSec = new DirectorySecurity(path, AccessControlSections.All);
             Directory.CreateDirectory(path, dirSec);
             //Directory.CreateDirectory(path);
         }
         return true;
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemplo n.º 42
0
 protected override void ExecuteOnDir(DirectoryInfo dir)
 {
     DirectorySecurity dirSec = new DirectorySecurity(dir.FullName, AccessControlSections.Access);
     IList<FileSystemAccessRule> targetRules = FindAccessRules(dirSec);
     if (targetRules.Count == 0)
     {
         Log(Level.Info, Resources.RemoveAccessRuleEmpty, NTAccount, dir.FullName);
     }
     else
     {
         foreach (FileSystemAccessRule fileSystemAccessRule in targetRules)
         {
             Log(Level.Info, Resources.RemoveAccessRuleRemoving, NTAccount, dir.FullName);
             dirSec.RemoveAccessRule(fileSystemAccessRule);
         }
         dir.SetAccessControl(dirSec);
     }
 }
Exemplo n.º 43
0
    /// <summary>
    /// 给文件夹添加完全控制权限
    /// </summary>
    /// <param name="directoryPath"></param>
    public static void AddTopPermissionToDirectory(string directoryPath)
    {
        if (string.IsNullOrEmpty(directoryPath))
        {
            return;
        }
        //给文件所在目录添加"Everyone,Users"用户组的完全控制权限
        DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(directoryPath));

        if (directoryInfo == null)
        {
            return;
        }
        System.Security.AccessControl.DirectorySecurity dirSecurity = directoryInfo.GetAccessControl();
        dirSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
        dirSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
        directoryInfo.SetAccessControl(dirSecurity);
    }
Exemplo n.º 44
0
        public static void Upload(string valor, string servidor, string fileName, string usuario, string senha, string diretorio, IEncoding type)
        {
            if (!string.IsNullOrEmpty(diretorio))
            {
                //object SpecialFolder = Activator.CreateInstance(Type.GetType("System.Environment+SpecialFolder"));
                //SpecialFolder.GetType().GetMember("Personal").GetValue(0);

                if (diretorio.Contains(":"))
                {
                    diretorio = diretorio + "\\" + fileName;//System.IO.Path.GetFileName(servidor);
                }
                else
                {
                    diretorio = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + diretorio;
                }

                string path = System.IO.Path.GetFullPath(diretorio);
                if (!System.IO.Directory.Exists(path))
                {
                    System.Security.AccessControl.DirectorySecurity sec = new System.Security.AccessControl.DirectorySecurity();
                    // Using this instead of the "Everyone" string means we work on non-English systems.
                    SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                    System.IO.Directory.CreateDirectory(path, sec);
                }
                type.SaveLocal(diretorio, fileName, valor);
                //System.IO.File.WriteAllText(diretorio+"\\"+System.IO.Path.GetFileName(servidor), valor);
            }

            if (!string.IsNullOrEmpty(servidor))
            {
                //FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(servidor));
                //request.Method = WebRequestMethods.Ftp.UploadFile;
                //request.Credentials = new NetworkCredential(usuario, senha);
                //Stream reqStream = null;

                //reqStream = request.GetRequestStream();
                //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(valor);
                //reqStream.Write(buffer, 0, buffer.Length);

                //reqStream.Close();
                type.SaveServer(servidor + "/" + fileName, usuario, senha, valor);
            }
        }
 public static bool setAccessControl(this DirectoryInfo directoryInfo, string targetUser, FileSystemRights fileSystemRights, AccessControlType accessControlType)
 {
     if (directoryInfo.notNull() && targetUser.notNull())
     {
         try
         {
             var fileSystemAccessRule = new FileSystemAccessRule(targetUser, fileSystemRights, accessControlType);
             var directorySecurity = new DirectorySecurity();
             directorySecurity.AddAccessRule(fileSystemAccessRule);
             directoryInfo.SetAccessControl(directorySecurity);
             return true;
         }
         catch(Exception ex)
         {
             ex.log();                    
         }
     }
     return false;
 }
Exemplo n.º 46
0
        private int CreaCartella(string path)
        {
            try
            {
                DirectoryInfo dir = Directory.CreateDirectory(path);
                var nn = new FileSystemAccessRule(@"tsf\TFSSetup", FileSystemRights.FullControl, AccessControlType.Allow);
                var u = new System.Security.Principal.NTAccount("tsf", "tfssetup");
                var dirSec = new DirectorySecurity();
                dirSec.AddAccessRule(nn);
                Directory.SetAccessControl(path, dirSec);
                var user = System.IO.Directory.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount));
                return 0;
            }
            catch(Exception ex)
            {
                throw ex;
            }

        }
Exemplo n.º 47
0
        private static DirectorySecurity GetDirectorySecurity(string fullControlMembers, string readWriteMembers)
        {
            System.Security.AccessControl.DirectorySecurity dirSecturity = new System.Security.AccessControl.DirectorySecurity();
            dirSecturity.SetAccessRuleProtection(true, false);      // Break inheritance and discard parent's access rules

            AddReadWriteAccess(dirSecturity, Environment.UserName); // Set Read/Write access for the current user

            System.Security.Principal.SecurityIdentifier systemSID = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.LocalSystemSid, null);
            AddAccessRule(dirSecturity, GetFullControlAccessRule(systemSID));   // Set Full Access for "System" Account

            if (!String.IsNullOrEmpty(readWriteMembers))
            {
                try
                {
                    foreach (string trustee in readWriteMembers.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        try
                        {
                            AddReadWriteAccess(dirSecturity, trustee);
                        }
                        catch (Exception ex) { Logger.Write(20015, "Unable to set Read/Write permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); }
                    }
                }
                catch (Exception ex) { Logger.Write(20015, "Unable to set Read/Write permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); }
            }

            if (!String.IsNullOrEmpty(fullControlMembers))
            {
                try
                {
                    foreach (string trustee in fullControlMembers.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        try
                        {
                            AddFullControlAccess(dirSecturity, trustee);
                        }
                        catch (Exception ex) { Logger.Write(20016, "Unable to set Full Control permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); }
                    }
                }
                catch (Exception ex) { Logger.Write(20016, "Unable to set Full Control permissions on destination folder. " + ex.Message, Logger.MessageSeverity.Error, System.Diagnostics.EventLogEntryType.Error); }
            }
            return(dirSecturity);
        }
Exemplo n.º 48
0
        /// <summary>
        ///为文件夹添加users,everyone用户组的完全控制权限
        /// </summary>
        /// <param name="dirPath"></param>
        public static void AddSecurityControllToFolder(string[] identities, string dirPath)
        {
            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(dirPath);

            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.Access);
            //设定文件ACL继承
            InheritanceFlags inherits   = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            bool             isModified = false;

            foreach (var item in identities)
            {
                FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(item, FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, fileSystemAccessRule, out isModified);
            }
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }
Exemplo n.º 49
0
        /// <summary>
        /// 为文件夹添加完全访问权限
        /// </summary>
        /// <param name="filepath">文件夹路径</param>
        public void addSecurityControl(string filepath)
        {
            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(filepath);

            //获得该文件夹的所有访问权限
            System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            //设定文件ACL继承
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //添加ereryone用户组的访问权限规则 完全控制权限
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            //添加Users用户组的访问权限规则 完全控制权限
            FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
            bool isModified = false;

            dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }
Exemplo n.º 50
0
 /// <summary>
 ///设置目录权限
 /// </summary>
 /// <param name="path">目录的路径。</param>
 /// <param name="permission">在目录上设置的权限。</param>
 /// <returns>指示是否在目录上应用权限的值。</returns>
 public bool SetDirectoryPermission(string path, FileSystemRights permission)
 {
     try
     {
         if (!Directory.Exists(path))
         {
             return(false);
         }
         //获取文件夹信息
         DirectoryInfo dir = new DirectoryInfo(path);
         //获得该文件夹的所有访问权限
         System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
         //设定文件ACL继承
         InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
         //添加ereryone用户组的访问权限规则 完全控制权限
         FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
         //添加Users用户组的访问权限规则 完全控制权限
         FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
         bool isModified = false;
         dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
         dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
         //设置访问权限
         dir.SetAccessControl(dirSecurity);
         return(true);
     }
     catch (Exception e)
     {
         //throw new Exception(e.Message, e);
         return(false);
     }
     //权限追加
     //fileAcl.AddAccessRule(everyoneRule);
     //权限删除
     //fileAcl.RemoveAccessRule(everyoneRule);
     //从当前文件或目录移除所有匹配的允许或拒绝访问控制列表 (ACL) 权限。
     //fileAcl.RemoveAccessRuleAll(everyoneRule);
     //从当前文件或目录移除指定用户的所有访问控制列表 (ACL) 权限。
     //fileAcl.RemoveAccessRuleSpecific(everyoneRule);
     //从当前文件或目录移除单个匹配的允许或拒绝访问控制列表 (ACL) 权限。
 }
Exemplo n.º 51
0
        /// <summary>
        /// 设置文件夹权限,处理为Everyone所有权限
        /// </summary>
        /// <param name="foldPath">文件夹路径</param>
        private void SetFileRole(string foldPath)
        {
            //DirectorySecurity fsec = new DirectorySecurity();
            //fsec.SetAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl,
            //InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
            //fsec.AddAccessRule(new FileSystemAccessRule
            //       ("Everyone", FileSystemRights.FullControl,
            //AccessControlType.Allow));
            //FileInfo fi = new FileInfo(foldPath);
            //FileSecurity fileSecurity = fi.GetAccessControl();
            //fileSecurity.AddAccessRule
            //    (new FileSystemAccessRule
            //        ("Everyone", FileSystemRights.FullControl,
            //        AccessControlType.Allow));
            //fi.SetAccessControl(fileSecurity);

            // 获取文件夹信息
            try
            {
                DirectoryInfo dir = new DirectoryInfo(foldPath);
                //获得该文件夹的所有访问权限
                System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
                //设定文件ACL继承
                InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
                //添加ereryone用户组的访问权限规则 完全控制权限
                FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
                //添加Users用户组的访问权限规则 完全控制权限
                FileSystemAccessRule usersFileSystemAccessRule = new FileSystemAccessRule("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
                bool isModified = false;
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
                dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out isModified);
                //设置访问权限
                dir.SetAccessControl(dirSecurity);
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 52
0
 /// <summary>
 ///为文件夹添加users用户组的完全控制权限
 /// </summary>
 /// <param name="dirPath"></param>
 private bool AddSecurityControll2Folder(string dirPath)
 {
     try
     {
         //获取文件夹信息
         DirectoryInfo dir = new DirectoryInfo(dirPath);
         //获得该文件夹的所有访问权限
         System.Security.AccessControl.DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
         //设定文件ACL继承
         InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
         //添加ereryone用户组的访问权限规则 完全控制权限
         FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule("IIS_IUSRS", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
         bool isModified = false;
         dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out isModified);
         //设置访问权限
         dir.SetAccessControl(dirSecurity);
         return(isModified);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Exemplo n.º 53
0
        public static bool AllowFolderAccess(string path, FileSystemRights rights)
        {
            try
            {
                var security    = Directory.GetAccessControl(path, AccessControlSections.Access);
                var usersSid    = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                var rules       = security.GetAccessRules(true, false, typeof(SecurityIdentifier));
                var inheritance = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;

                foreach (FileSystemAccessRule rule in rules)
                {
                    if (rule.IdentityReference == usersSid)
                    {
                        if (rule.AccessControlType == AccessControlType.Allow)
                        {
                            if ((rule.FileSystemRights & rights) == rights && (rule.InheritanceFlags & inheritance) == inheritance)
                            {
                                return(true);
                            }
                            rights |= rule.FileSystemRights;
                        }
                        break;
                    }
                }

                security = new System.Security.AccessControl.DirectorySecurity();
                security.AddAccessRule(new FileSystemAccessRule(usersSid, rights, inheritance, PropagationFlags.None, AccessControlType.Allow));
                Directory.SetAccessControl(path, security);

                return(true);
            }
            catch (Exception e)
            {
                Util.Logging.Log(e);
                return(false);
            }
        }
Exemplo n.º 54
0
 public static void SetAccessControl(this System.IO.DirectoryInfo directoryInfo, System.Security.AccessControl.DirectorySecurity directorySecurity)
 {
 }
Exemplo n.º 55
0
 public static System.IO.DirectoryInfo CreateDirectory(this System.Security.AccessControl.DirectorySecurity directorySecurity, string path)
 {
     throw null;
 }
Exemplo n.º 56
0
        private static DirectorySecurity GetMySecure()
        {
            var mySecure = new System.Security.AccessControl.DirectorySecurity();

            return(mySecure);
        }
Exemplo n.º 57
0
 public static DirectoryInfo CreateDirectory(string path, System.Security.AccessControl.DirectorySecurity directorySecurity)
 => CreateDirectory(path);                  //ignore directorySecurity
Exemplo n.º 58
0
 public void Create(System.Security.AccessControl.DirectorySecurity directorySecurity)
 => FileSystem.CreateDirectory(FullPath);                  // ignore directorySecurity
Exemplo n.º 59
0
 => FileSystem.CreateDirectory(FullPath);                  // ignore directorySecurity
 public DirectoryInfo CreateSubdirectory(string path, System.Security.AccessControl.DirectorySecurity directorySecurity)
 => CreateSubdirectory(path);
Exemplo n.º 60
0
        private void hide_Click(object sender, EventArgs e)
        {
            Thread hideThread = new Thread((ThreadStart)(delegate()
            {
                string targetFolder = ".\\" + textBox1.Text;
                string desktoppath = targetFolder + "\\" + "desktop.ini";
                string wzh = @".\回收站.{645ff040-5081-101b-9f08-00aa002f954e}";
                string user = "******";
                string pw = targetFolder + "\\" + "astSetting.ini";
                if (textBox1.Text == "")
                {
                    MessageBox.Show("你貌似忘了戴套了?", "出错!");
                }
                else if (Directory.Exists(wzh))
                {
                    MessageBox.Show("此目录下已存在隐藏文件夹!", "警告!");
                }
                else if (Directory.Exists(targetFolder))
                {
                    label1.Text = "程序执行中,请稍后......\r\n执行过程中请不要操作本程序以及强制停止本程序!\r\n花费的时间和文件数量成正比,零散文件越多,花费时间将会越长。";
                    var key = "=9bn&2g=4By3^GrCsP;oVQat/*6o%l#R"; //定义使用的密匙
                    var jmh = Encrypt(key, textBox1.Text);        //加密textBox1的文本
                    if (File.Exists(pw))
                    {
                        File.Delete(pw);
                    }
                    if (File.Exists(desktoppath))
                    {
                        File.Delete(desktoppath);
                    }
                    try
                    {
                        //写入desktop.ini文件
                        StreamWriter desktop = new StreamWriter(desktoppath, false, Encoding.Default);
                        desktop.WriteLine("[.ShellClassInfo]");
                        desktop.WriteLine("CLSID={645FF040-5081-101B-9F08-00AA002F954E}");
                        desktop.WriteLine("LocalizedResourceName=@%SystemRoot%\\system32\\shell32.dll,-8964");
                        desktop.Close();
                        //写入程序配置astSetting.ini文件
                        StreamWriter spw = new StreamWriter(pw, false, Encoding.UTF8);
                        spw.WriteLine(jmh);
                        spw.Close();
                        //设置文件夹所有者
                        DirectoryInfo ad = new DirectoryInfo(targetFolder);
                        DirectorySecurity adm = ad.GetAccessControl();
                        NTAccount admin = new NTAccount("Administrators");    //管理员组
                        adm.SetOwner(admin);
                        //<--设置文件夹权限
                        System.Security.AccessControl.DirectorySecurity tf;
                        tf = new System.Security.AccessControl.DirectorySecurity();
                        tf.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Deny));
                        System.IO.Directory.SetAccessControl(targetFolder, tf);
                        //设置权限是为了防止被第三方文件浏览器查看到-->
                        DirectoryInfo wz = new DirectoryInfo(targetFolder);
                        wz.MoveTo(wzh);                                                            //重命名文件夹以伪装成回收站
                        File.SetAttributes(wzh, FileAttributes.System | FileAttributes.Hidden);    //隐藏为受保护的系统文件
                        x = 1;
                    }
                    catch
                    {
                        if (Directory.Exists(targetFolder))
                        {
                            File.SetAttributes(targetFolder, FileAttributes.Normal);        //恢复文件夹访问权限
                            System.Security.AccessControl.DirectorySecurity tf;
                            tf = new System.Security.AccessControl.DirectorySecurity();
                            tf.RemoveAccessRule(new FileSystemAccessRule(user, FileSystemRights.Read, AccessControlType.Deny));
                            System.IO.Directory.SetAccessControl(targetFolder, tf);
                        }
                        MessageBox.Show("出现几率极低的未知错误,未能完美执行!程序将自动执行回滚操作。", "注意!");
                        label1.Text = "操作错误,失败!";
                    }
                    if (x == 1)
                    {
                        MessageBox.Show("操作成功!", "恭喜!");
                        label1.Text = "注意:\r\n本工具采用的是“密码=文件夹名”的方式,建议文件夹名包含数字、符号或字母。";
                    }
                    else
                    {
                        if (File.Exists(pw))
                        {
                            File.Delete(pw);
                        }
                        if (File.Exists(desktoppath))
                        {
                            File.Delete(desktoppath);
                        }
                        MessageBox.Show("操作失败!\n请确定你是该文件夹的所有者,你拥有足够的权限且此文件夹没有被其他进程占用!", "失败了!");
                        label1.Text = "一般情况下本程序都能够完美成功执行任务,只有极少数特殊情况下才会失败。";
                    }
                }
                else
                {
                    MessageBox.Show("文件夹不存在!", "文件夹名错误!");
                }
            }));

            hideThread.Start();
        }