Пример #1
0
        /// <summary>Returns the directory information for the specified path string.</summary>
        /// <returns>A <see cref="T:System.String" /> containing directory information for <paramref name="path" />, or null if <paramref name="path" /> denotes a root directory or is null. Returns <see cref="F:System.String.Empty" /> if <paramref name="path" /> does not contain directory information.</returns>
        /// <param name="path">The path of a file or directory. </param>
        /// <exception cref="T:System.ArgumentException">The <paramref name="path" /> parameter contains invalid characters, is empty, or contains only white spaces. </exception>
        /// <exception cref="T:System.IO.PathTooLongException">The <paramref name="path" /> parameter is longer than the system-defined maximum length.</exception>
        /// <filterpriority>1</filterpriority>
        public static string GetDirectoryName(string path)
        {
            if (path == string.Empty)
            {
                throw new ArgumentException("Invalid path");
            }
            if (path == null || Path.GetPathRoot(path) == path)
            {
                return(null);
            }
            if (path.Trim().Length == 0)
            {
                throw new ArgumentException("Argument string consists of whitespace characters only.");
            }
            if (path.IndexOfAny(Path.InvalidPathChars) > -1)
            {
                throw new ArgumentException("Path contains invalid characters");
            }
            int num = path.LastIndexOfAny(Path.PathSeparatorChars);

            if (num == 0)
            {
                num++;
            }
            if (num <= 0)
            {
                return(string.Empty);
            }
            string text   = path.Substring(0, num);
            int    length = text.Length;

            if (length >= 2 && Path.DirectorySeparatorChar == '\\' && text[length - 1] == Path.VolumeSeparatorChar)
            {
                return(text + Path.DirectorySeparatorChar);
            }
            return(Path.CleanPath(text));
        }