public MyFolder GetSpecifiedFolder(string folderpath)
        {
            MyFolder myfolder = new MyFolder();

            myfolder.Path = folderpath;
            DirectoryInfo di = new DirectoryInfo(folderpath);

            myfolder.Name         = di.Name;
            myfolder.LastModified = di.LastWriteTimeUtc;
            DirectorySecurity sec = di.GetAccessControl();

            myfolder.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
            myfolder.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();
            return(myfolder);
        }
        /// <summary>Creates a new directory, ensuring it is created with the specified directory security. If the directory already exists, nothing is done.</summary>
        /// <param name="directoryInfo">The object describing a directory that does not exist in disk yet.</param>
        /// <param name="directorySecurity">An object that determines the access control and audit security for the directory.</param>
        /// <exception cref="ArgumentNullException"><paramref name="directoryInfo" /> or <paramref name="directorySecurity" /> is <see langword="null" />.</exception>
        /// <exception cref="DirectoryNotFoundException">Could not find a part of the path.</exception>
        /// <exception cref="UnauthorizedAccessException">Access to the path is denied.</exception>
        /// <remarks>This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.DirectoryInfo.Create(System.Security.AccessControl.DirectorySecurity)` .NET Framework method.</remarks>
        public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity)
        {
            ArgumentNullException.ThrowIfNull(directoryInfo);
            ArgumentNullException.ThrowIfNull(directorySecurity);

            FileSystem.CreateDirectory(directoryInfo.FullName, directorySecurity.GetSecurityDescriptorBinaryForm());
        }
Example #3
0
            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));
            }
Example #4
0
        public void TestCreate()
        {
            //Arrange
            var fs  = new MockFileSystem();
            var dir = @"c:\my\dir";

            //Act
            var s = new DirectorySecurity();
            var d = s.GetSecurityDescriptorBinaryForm();

            _ = new DirectoryActions(fs).Create(dir, 0, d, out var e);

            //Assert
            Assert.IsTrue(fs.Directory.Exists(@"c:\my\dir"));
            Assert.IsTrue(fs.Directory.Exists(@"c:\my\dir"));
            Assert.AreEqual(0, e.AllocationSize);
            Assert.AreEqual((uint)fs.DirectoryInfo.FromDirectoryName(dir).Attributes, e.Attributes);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(dir).LastWriteTimeUtc.ToFileTimeUtc(), e.ChangeTime);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(dir).CreationTimeUtc.ToFileTimeUtc(), e.CreationTime);
            Assert.AreEqual(0, e.EaSize);
            Assert.AreEqual(0, e.FileSize);
            Assert.AreEqual(0, e.HardLinks);
            Assert.AreEqual(0, e.IndexNumber);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(dir).LastAccessTimeUtc.ToFileTimeUtc(), e.LastAccessTime);
            Assert.AreEqual(fs.DirectoryInfo.FromDirectoryName(dir).LastWriteTimeUtc.ToFileTimeUtc(), e.LastWriteTime);
            Assert.AreEqual(0, e.ReparseTag);
            Assert.IsFalse(e.IsFile());
        }
        public MyFolder[] GetRootFolders()
        {
            List <MyFolder> myFolders = new List <MyFolder>();

            MyFolder myfolder = new MyFolder();

            myfolder.Path = this.path;
            DirectoryInfo di = new DirectoryInfo(path);

            myfolder.Name         = di.Name;
            myfolder.LastModified = di.LastWriteTimeUtc;
            DirectorySecurity sec = di.GetAccessControl();

            myfolder.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
            myfolder.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();

            myFolders.Add(myfolder);
            return(myFolders.ToArray());
        }
        public MyFolder[] GetSubFolders(string parentFolderPath)
        {
            List <MyFolder> myFolders = new List <MyFolder>();

            foreach (string dirpath in Directory.GetDirectories(parentFolderPath))
            {
                MyFolder myfolder = new MyFolder();
                myfolder.Path = dirpath;
                DirectoryInfo di = new DirectoryInfo(dirpath);
                myfolder.Name         = di.Name;
                myfolder.LastModified = di.LastWriteTimeUtc;
                DirectorySecurity sec = di.GetAccessControl();
                myfolder.SecurityDesciptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
                myfolder.SecurityDesciptor = sec.GetSecurityDescriptorBinaryForm();

                myFolders.Add(myfolder);
            }
            return(myFolders.ToArray());
        }
Example #7
0
        public MyFolder GetSpecifiedFolder(string folderpath)
        {
            if (!Directory.Exists(folderpath))
            {
                throw new Microsoft.BusinessData.Runtime.ObjectNotFoundException(String.Format(
                                                                                     "No folder exists at the path {0}",
                                                                                     folderpath));
            }

            MyFolder myfolder = new MyFolder();

            myfolder.Path = folderpath;
            DirectoryInfo di = new DirectoryInfo(folderpath);

            myfolder.Name         = di.Name;
            myfolder.LastModified = di.LastWriteTimeUtc;
            DirectorySecurity sec = di.GetAccessControl();

            myfolder.SecurityDescriptor = new Byte[sec.GetSecurityDescriptorBinaryForm().Length];
            myfolder.SecurityDescriptor = sec.GetSecurityDescriptorBinaryForm();
            return(myfolder);
        }
Example #8
0
        /// <summary>Creates a new directory, ensuring it is created with the specified directory security. If the directory already exists, nothing is done.</summary>
        /// <param name="directoryInfo">The object describing a directory that does not exist in disk yet.</param>
        /// <param name="directorySecurity">An object that determines the access control and audit security for the directory.</param>
        /// <exception cref="ArgumentNullException"><paramref name="directoryInfo" /> or <paramref name="directorySecurity" /> is <see langword="null" />.</exception>
        /// <exception cref="DirectoryNotFoundException">Could not find a part of the path.</exception>
        /// <exception cref="UnauthorizedAccessException">Access to the path is denied.</exception>
        /// <remarks>This extension method was added to .NET Core to bring the functionality that was provided by the `System.IO.DirectoryInfo.Create(System.Security.AccessControl.DirectorySecurity)` .NET Framework method.</remarks>
        public static void Create(this DirectoryInfo directoryInfo, DirectorySecurity directorySecurity)
        {
            if (directoryInfo == null)
            {
                throw new ArgumentNullException(nameof(directoryInfo));
            }

            if (directorySecurity == null)
            {
                throw new ArgumentNullException(nameof(directorySecurity));
            }

            FileSystem.CreateDirectory(directoryInfo.FullName, directorySecurity.GetSecurityDescriptorBinaryForm());
        }
Example #9
0
        public void GetAccessControl1()
        {
            string path = Path.Combine(Path.GetTempPath(), "CadruTest");

            Directory.CreateDirectory(path);
            DirectoryInfo di = new DirectoryInfo(path);

            ExtendedDirectoryInfo edi = new ExtendedDirectoryInfo(path);

            Assert.IsNotNull(edi);

            DirectorySecurity actual   = edi.GetAccessControl(AccessControlSections.All);
            DirectorySecurity expected = di.GetAccessControl(AccessControlSections.All);

            CollectionAssert.AreEqual(expected.GetSecurityDescriptorBinaryForm(), actual.GetSecurityDescriptorBinaryForm());
        }
        public void TestAccessDenied()
        {
            string child2 = Path.Combine(TestFolder, @"child1\child2");

            DirectorySecurity acl = Directory.GetAccessControl(child2);

            byte[] original = acl.GetSecurityDescriptorBinaryForm();
            acl.AddAccessRule(
                new FileSystemAccessRule(
                    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                    FileSystemRights.ListDirectory,
                    AccessControlType.Deny)
                );
            Directory.SetAccessControl(child2, acl);
            try
            {
                //By default it ignores AccessDenied
                FindFile ff = new FindFile(child2, "*", false, false);
                ff.FileFound += (o, e) => Assert.Fail("Should not find a file");
                ff.Find();

                //Now raise the AccessDenied
                ff.RaiseOnAccessDenied = true;
                try
                {
                    ff.Find();
                    Assert.Fail("Should throw Access Denied.");
                }
                catch (System.ComponentModel.Win32Exception we)
                { Assert.AreEqual(5, we.NativeErrorCode); }
            }
            finally
            {
                acl.SetSecurityDescriptorBinaryForm(original, AccessControlSections.All);
                Directory.SetAccessControl(child2, acl);
            }
        }
Example #11
0
        public void SetAccessControl()
        {
            string path = Path.Combine(Path.GetTempPath(), "CadruTest");

            Directory.CreateDirectory(path);

            DirectoryInfo     di       = new DirectoryInfo(path);
            DirectorySecurity expected = di.GetAccessControl(AccessControlSections.All);

            ExtendedDirectoryInfo edi = new ExtendedDirectoryInfo(path);

            Assert.IsNotNull(edi);

            DirectorySecurity directorySecurity = new DirectorySecurity();

            directorySecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));

            edi.SetAccessControl(directorySecurity);

            Assert.AreNotEqual(expected.GetSecurityDescriptorBinaryForm(), edi.GetAccessControl().GetSecurityDescriptorBinaryForm());

            DirectorySecurity           actualDirectorySecurity = Directory.GetAccessControl(path);
            AuthorizationRuleCollection rules = actualDirectorySecurity.GetAccessRules(true, true, typeof(NTAccount));

            foreach (AuthorizationRule rule in rules)
            {
                FileSystemAccessRule accessRule = (FileSystemAccessRule)rule;

                if (accessRule.IdentityReference.Value == "Everyone")
                {
                    Assert.IsTrue(accessRule.AccessControlType == AccessControlType.Allow);
                    Assert.IsTrue(accessRule.FileSystemRights == FileSystemRights.FullControl);
                }
            }

            di.SetAccessControl(expected);
        }
        private unsafe static void InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj)
        {
#if FEATURE_MACL
            DirectorySecurity dirSecurity = (DirectorySecurity)dirSecurityObj;
#endif // FEATURE_MACL

            int length = fullPath.Length;

            // We need to trim the trailing slash or the code will try to create 2 directories of the same name.
            if (length >= 2 && Path.IsDirectorySeparator(fullPath[length - 1]))
            {
                length--;
            }

            int lengthRoot = LongPath.GetRootLength(fullPath);

#if !PLATFORM_UNIX
            // For UNC paths that are only // or ///
            if (length == 2 && Path.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", path));
            }
#endif // !PLATFORM_UNIX

            List <string> stackDir = new List <string>();

            // Attempt to figure out which directories don't exist, and only
            // create the ones we need.  Note that InternalExists may fail due
            // to Win32 ACL's preventing us from seeing a directory, and this
            // isn't threadsafe.

            bool somepathexists = false;

            if (length > lengthRoot)
            { // Special case root (fullpath = X:\\)
                int i = length - 1;
                while (i >= lengthRoot && !somepathexists)
                {
                    String dir = fullPath.Substring(0, i + 1);

                    if (!InternalExists(dir)) // Create only the ones missing
                    {
                        stackDir.Add(dir);
                    }
                    else
                    {
                        somepathexists = true;
                    }

                    while (i > lengthRoot && fullPath[i] != Path.DirectorySeparatorChar && fullPath[i] != Path.AltDirectorySeparatorChar)
                    {
                        i--;
                    }
                    i--;
                }
            }

            int count = stackDir.Count;

            if (stackDir.Count != 0)
            {
                String[] securityList = new String[stackDir.Count];
                stackDir.CopyTo(securityList, 0);
                for (int j = 0; j < securityList.Length; j++)
                {
                    securityList[j] += "\\."; // leaf will never have a slash at the end
                }
                // Security check for all directories not present only.
#if !FEATURE_PAL && FEATURE_MACL
                AccessControlActions control = (dirSecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
                new FileIOPermission(FileIOPermissionAccess.Write, control, securityList, false, false).Demand();
#else
                new FileIOPermission(FileIOPermissionAccess.Write, securityList, false, false).Demand();
#endif
            }

            // If we were passed a DirectorySecurity, convert it to a security
            // descriptor and set it in he call to CreateDirectory.
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
            if (dirSecurity != null)
            {
                secAttrs         = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                // For ACL's, get the security descriptor from the FileSecurity.
                byte[] sd           = dirSecurity.GetSecurityDescriptorBinaryForm();
                byte * bytesOnStack = stackalloc byte[sd.Length];
                Buffer.Memcpy(bytesOnStack, 0, sd, 0, sd.Length);
                secAttrs.pSecurityDescriptor = bytesOnStack;
            }
#endif

            bool   r           = true;
            int    firstError  = 0;
            String errorString = path;
            // If all the security checks succeeded create all the directories
            while (stackDir.Count > 0)
            {
                String name = stackDir[stackDir.Count - 1];
                stackDir.RemoveAt(stackDir.Count - 1);
                if (name.Length >= Path.MaxLongPath)
                {
                    throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                }
                r = Win32Native.CreateDirectory(Path.AddLongPathPrefix(name), secAttrs);
                if (!r && (firstError == 0))
                {
                    int currentError = Marshal.GetLastWin32Error();
                    // While we tried to avoid creating directories that don't
                    // exist above, there are at least two cases that will
                    // cause us to see ERROR_ALREADY_EXISTS here.  InternalExists
                    // can fail because we didn't have permission to the
                    // directory.  Secondly, another thread or process could
                    // create the directory between the time we check and the
                    // time we try using the directory.  Thirdly, it could
                    // fail because the target does exist, but is a file.
                    if (currentError != Win32Native.ERROR_ALREADY_EXISTS)
                    {
                        firstError = currentError;
                    }
                    else
                    {
                        // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
                        if (LongPathFile.InternalExists(name) || (!InternalExists(name, out currentError) && currentError == Win32Native.ERROR_ACCESS_DENIED))
                        {
                            firstError = currentError;
                            // Give the user a nice error message, but don't leak path information.
                            try
                            {
                                new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { GetDemandDir(name, true) }, false, false).Demand();
                                errorString = name;
                            }
                            catch (SecurityException) { }
                        }
                    }
                }
            }

            // We need this check to mask OS differences
            // Handle CreateDirectory("X:\\foo") when X: doesn't exist. Similarly for n/w paths.
            if ((count == 0) && !somepathexists)
            {
                String root = InternalGetDirectoryRoot(fullPath);
                if (!InternalExists(root))
                {
                    // Extract the root from the passed in path again for security.
                    __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, InternalGetDirectoryRoot(path));
                }
                return;
            }

            // Only throw an exception if creating the exact directory we
            // wanted failed to work correctly.
            if (!r && (firstError != 0))
            {
                __Error.WinIOError(firstError, errorString);
            }
        }
Example #13
0
        private static unsafe void InternalCreateDirectory(string fullPath, string path, object dirSecurityObj)
        {
            DirectorySecurity security = (DirectorySecurity)dirSecurityObj;
            int length = fullPath.Length;

            if ((length >= 2) && Path.IsDirectorySeparator(fullPath[length - 1]))
            {
                length--;
            }
            int rootLength = LongPath.GetRootLength(fullPath);

            if ((length == 2) && Path.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", new object[] { path }));
            }
            List <string> list = new List <string>();
            bool          flag = false;

            if (length > rootLength)
            {
                for (int i = length - 1; (i >= rootLength) && !flag; i--)
                {
                    string str = fullPath.Substring(0, i + 1);
                    if (!InternalExists(str))
                    {
                        list.Add(str);
                    }
                    else
                    {
                        flag = true;
                    }
                    while (((i > rootLength) && (fullPath[i] != Path.DirectorySeparatorChar)) && (fullPath[i] != Path.AltDirectorySeparatorChar))
                    {
                        i--;
                    }
                }
            }
            int count = list.Count;

            if (list.Count != 0)
            {
                string[] array = new string[list.Count];
                list.CopyTo(array, 0);
                for (int j = 0; j < array.Length; j++)
                {
                    string[] strArray2;
                    IntPtr   ptr;
                    (strArray2 = array)[(int)(ptr = (IntPtr)j)] = strArray2[(int)ptr] + @"\.";
                }
                AccessControlActions control = (security == null) ? AccessControlActions.None : AccessControlActions.Change;
                new FileIOPermission(FileIOPermissionAccess.Write, control, array, false, false).Demand();
            }
            Win32Native.SECURITY_ATTRIBUTES structure = null;
            if (security != null)
            {
                structure = new Win32Native.SECURITY_ATTRIBUTES {
                    nLength = Marshal.SizeOf(structure)
                };
                byte[] securityDescriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
                byte * pDest = stackalloc byte[(IntPtr)securityDescriptorBinaryForm.Length];
                Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
                structure.pSecurityDescriptor = pDest;
            }
            bool   flag2         = true;
            int    errorCode     = 0;
            string maybeFullPath = path;

            while (list.Count > 0)
            {
                string str3 = list[list.Count - 1];
                list.RemoveAt(list.Count - 1);
                if (str3.Length >= Path.MaxLongPath)
                {
                    throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                }
                flag2 = Win32Native.CreateDirectory(Path.AddLongPathPrefix(str3), structure);
                if (!flag2 && (errorCode == 0))
                {
                    int lastError = Marshal.GetLastWin32Error();
                    if (lastError != 0xb7)
                    {
                        errorCode = lastError;
                    }
                    else if (LongPathFile.InternalExists(str3) || (!InternalExists(str3, out lastError) && (lastError == 5)))
                    {
                        errorCode = lastError;
                        try
                        {
                            new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] { GetDemandDir(str3, true) }, false, false).Demand();
                            maybeFullPath = str3;
                            continue;
                        }
                        catch (SecurityException)
                        {
                            continue;
                        }
                    }
                }
            }
            if ((count == 0) && !flag)
            {
                if (!InternalExists(InternalGetDirectoryRoot(fullPath)))
                {
                    __Error.WinIOError(3, InternalGetDirectoryRoot(path));
                }
            }
            else if (!flag2 && (errorCode != 0))
            {
                __Error.WinIOError(errorCode, maybeFullPath);
            }
        }
Example #14
0
        private unsafe static void InternalCreateDirectory(string fullPath, string path, object dirSecurityObj)
        {
            DirectorySecurity directorySecurity = (DirectorySecurity)dirSecurityObj;
            int num = fullPath.Length;

            if (num >= 2 && Path.IsDirectorySeparator(fullPath[num - 1]))
            {
                num--;
            }
            int rootLength = LongPath.GetRootLength(fullPath);

            if (num == 2 && Path.IsDirectorySeparator(fullPath[1]))
            {
                throw new IOException(Environment.GetResourceString("IO.IO_CannotCreateDirectory", new object[]
                {
                    path
                }));
            }
            List <string> list = new List <string>();
            bool          flag = false;

            if (num > rootLength)
            {
                int num2 = num - 1;
                while (num2 >= rootLength && !flag)
                {
                    string text = fullPath.Substring(0, num2 + 1);
                    if (!LongPathDirectory.InternalExists(text))
                    {
                        list.Add(text);
                    }
                    else
                    {
                        flag = true;
                    }
                    while (num2 > rootLength && fullPath[num2] != Path.DirectorySeparatorChar && fullPath[num2] != Path.AltDirectorySeparatorChar)
                    {
                        num2--;
                    }
                    num2--;
                }
            }
            int count = list.Count;

            if (list.Count != 0 && !CodeAccessSecurityEngine.QuickCheckForAllDemands())
            {
                string[] array = new string[list.Count];
                list.CopyTo(array, 0);
                for (int i = 0; i < array.Length; i++)
                {
                    string[] array2 = array;
                    int      num3   = i;
                    array2[num3] += "\\.";
                }
                AccessControlActions control = (directorySecurity == null) ? AccessControlActions.None : AccessControlActions.Change;
                FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, control, array, false, false);
            }
            Win32Native.SECURITY_ATTRIBUTES security_ATTRIBUTES = null;
            if (directorySecurity != null)
            {
                security_ATTRIBUTES         = new Win32Native.SECURITY_ATTRIBUTES();
                security_ATTRIBUTES.nLength = Marshal.SizeOf <Win32Native.SECURITY_ATTRIBUTES>(security_ATTRIBUTES);
                byte[] securityDescriptorBinaryForm = directorySecurity.GetSecurityDescriptorBinaryForm();
                byte * ptr = stackalloc byte[checked (unchecked ((UIntPtr)securityDescriptorBinaryForm.Length) * 1)];
                Buffer.Memcpy(ptr, 0, securityDescriptorBinaryForm, 0, securityDescriptorBinaryForm.Length);
                security_ATTRIBUTES.pSecurityDescriptor = ptr;
            }
            bool   flag2         = true;
            int    num4          = 0;
            string maybeFullPath = path;

            while (list.Count > 0)
            {
                string text2 = list[list.Count - 1];
                list.RemoveAt(list.Count - 1);
                if (text2.Length >= 32767)
                {
                    throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
                }
                flag2 = Win32Native.CreateDirectory(PathInternal.EnsureExtendedPrefix(text2), security_ATTRIBUTES);
                if (!flag2 && num4 == 0)
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    if (lastWin32Error != 183)
                    {
                        num4 = lastWin32Error;
                    }
                    else if (LongPathFile.InternalExists(text2) || (!LongPathDirectory.InternalExists(text2, out lastWin32Error) && lastWin32Error == 5))
                    {
                        num4 = lastWin32Error;
                        try
                        {
                            FileIOPermission.QuickDemand(FileIOPermissionAccess.PathDiscovery, LongPathDirectory.GetDemandDir(text2, true), false, false);
                            maybeFullPath = text2;
                        }
                        catch (SecurityException)
                        {
                        }
                    }
                }
            }
            if (count == 0 && !flag)
            {
                string path2 = LongPathDirectory.InternalGetDirectoryRoot(fullPath);
                if (!LongPathDirectory.InternalExists(path2))
                {
                    __Error.WinIOError(3, LongPathDirectory.InternalGetDirectoryRoot(path));
                }
                return;
            }
            if (!flag2 && num4 != 0)
            {
                __Error.WinIOError(num4, maybeFullPath);
            }
        }
Example #15
0
        public void Create()
        {
            FileShareWitnessCheckResult fileShareWitnessCheckResult = this.Check();

            if (fileShareWitnessCheckResult != FileShareWitnessCheckResult.FswOK)
            {
                FileSystemSecurity fileSystemSecurity = new DirectorySecurity();
                foreach (FileSystemAccessRule rule in this.AccessRules)
                {
                    fileSystemSecurity.AddAccessRule(rule);
                }
                switch (fileShareWitnessCheckResult)
                {
                case FileShareWitnessCheckResult.FswDoesNotExist:
                    try
                    {
                        TaskLogger.Trace("Attempting to create new witness share \\\\{0}\\{1}.", new object[]
                        {
                            this.WitnessServer,
                            this.ShareName
                        });
                        WmiWrapper.CreateDirectory(this.WitnessServerFqdn, this.WitnessDirectory.ToString());
                        int num;
                        NetShare.AddShare(string.Format(FileShareWitness.s_hostNameFormat, this.WitnessServerFqdn), null, this.ShareName, this.WitnessDirectory.ToString(), this.m_shareRemark, fileSystemSecurity.GetSecurityDescriptorBinaryForm(), out num);
                        this.m_existingShareRemark      = this.m_shareRemark;
                        this.m_shareType                = 0U;
                        this.m_sharePermissions         = 1;
                        this.m_shareMaxUses             = -1;
                        this.m_existingWitnessDirectory = this.WitnessDirectory;
                        this.m_existingSecurity         = fileSystemSecurity;
                        this.m_exists        = new bool?(true);
                        this.m_isJustCreated = true;
                        TaskLogger.Trace("Attempt to create new witness share \\\\{0}\\{1} succeeded.", new object[]
                        {
                            this.WitnessServer,
                            this.ShareName
                        });
                        return;
                    }
                    catch (WmiException ex)
                    {
                        throw new DagFswUnableToCreateWitnessDirectoryException(this.WitnessServerFqdn, this.WitnessDirectory.ToString(), ex);
                    }
                    catch (Win32Exception ex2)
                    {
                        throw new DagFswUnableToCreateWitnessShareException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex2);
                    }
                    break;

                case FileShareWitnessCheckResult.FswWrongDirectory:
                    goto IL_1C1;

                case FileShareWitnessCheckResult.FswWrongPermissions:
                    break;

                default:
                    return;
                }
                fileSystemSecurity = this.m_existingSecurity;
                foreach (FileSystemAccessRule rule2 in this.AccessRules)
                {
                    fileSystemSecurity.AddAccessRule(rule2);
                }
                try
                {
IL_1C1:
                    TaskLogger.Trace("Attempting to modify permissions on witness share \\\\{0}\\{1}.", new object[]
                    {
                        this.WitnessServer,
                        this.ShareName
                    });
                    NetShare.SetShareInfo(this.WitnessServerFqdn, this.ShareName, this.WitnessDirectory.ToString(), this.m_shareRemark, this.m_shareType, this.m_sharePermissions, -1, fileSystemSecurity.GetSecurityDescriptorBinaryForm());
                    this.m_existingWitnessDirectory = this.WitnessDirectory;
                    this.m_existingSecurity         = fileSystemSecurity;
                    this.m_shareMaxUses             = -1;
                    this.m_exists = new bool?(true);
                    TaskLogger.Trace("Attempt to modify permissions on witness share \\\\{0}\\{1} succeeded.", new object[]
                    {
                        this.WitnessServer,
                        this.ShareName
                    });
                }
                catch (Win32Exception ex3)
                {
                    throw new DagFswUnableToUpdateWitnessShareException(this.WitnessServerFqdn, this.FileShareWitnessShare.ToString(), ex3);
                }
            }
        }