- Directory Info. Create Метод
- Определение
- Перегрузки
- Create()
- Исключения
- Примеры
- Комментарии
- Применяется к
- Create(DirectorySecurity)
- Параметры
- Исключения
- Примеры
- Комментарии
- CreateDirectoryExA function (winbase.h)
- Syntax
- Parameters
- Return value
- Remarks
- mkdir mkdir
- Синтаксис Syntax
- Параметры Parameters
- Примеры Examples
- Creating an Application Directory Partition
- Locating the Partitions Container
Directory Info. Create Метод
Определение
Создает каталог. Creates a directory.
Перегрузки
Создает каталог. Creates a directory.
Создает каталог с помощью объекта DirectorySecurity. Creates a directory using a DirectorySecurity object.
Create()
Создает каталог. Creates a directory.
Исключения
Не удалось создать каталог. The directory cannot be created.
Примеры
Следующий пример проверяет, существует ли указанный каталог, создает каталог, если он не существует, и удаляет каталог. The following example checks whether a specified directory exists, creates the directory if it does not exist, and deletes the directory.
Комментарии
Если каталог уже существует, этот метод не выполняет никаких действий. If the directory already exists, this method does nothing.
Если каталог не существовал до вызова этого метода, все кэшированные сведения об атрибуте каталога будут сброшены, если создание прошло успешно. If the directory did not exist before calling this method, then any cached attribute information about the directory will be flushed if the creation is successful.
Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода. For a list of common I/O tasks, see Common I/O Tasks.
Применяется к
Create(DirectorySecurity)
Создает каталог с помощью объекта DirectorySecurity. Creates a directory using a DirectorySecurity object.
Параметры
Элемент управления доступом, который необходимо применить к каталогу. The access control to apply to the directory.
Исключения
Каталог, заданный параметром path , доступен только для чтения или не является пустым каталогом. The directory specified by path is read-only or is not empty.
У вызывающего объекта отсутствует необходимое разрешение. The caller does not have the required permission.
path представляет собой строку нулевой длины, содержащую только пробелы или один или несколько недопустимых символов, заданных методом InvalidPathChars. path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.
path имеет значение null . path is null .
Указанный путь, имя файла или оба значения превышают максимальную длину, заданную в системе. The specified path, file name, or both exceed the system-defined maximum length.
Указан недопустимый путь (например, он ведет на несопоставленный диск). The specified path is invalid, such as being on an unmapped drive.
Предпринята попытка создать каталог с единственным знаком двоеточия (:). Creating a directory with only the colon (:) character was attempted.
Примеры
В следующем примере кода создается новый каталог внутри временной папки пользователя с указанными атрибутами безопасности каталога: The following code example creates a new directory inside the user’s temporary folder with the specified directory security attributes:
Комментарии
Используйте эту перегрузку метода для создания каталога с контролем доступа, поэтому нет возможности получить доступ к каталогу до применения безопасности. Use this method overload to create a directory with access control, so there is no chance the directory can be accessed before security is applied.
Если каталог уже существует, этот метод не выполняет никаких действий. If the directory already exists, this method does nothing.
Список общих задач ввода-вывода см. в разделе Общие задачи ввода-вывода. For a list of common I/O tasks, see Common I/O Tasks.
CreateDirectoryExA function (winbase.h)
Creates a new directory with the attributes of a specified template directory. If the underlying file system supports security on files and directories, the function applies a specified security descriptor to the new directory. The new directory retains the other attributes of the specified template directory.
To perform this operation as a transacted operation, use the CreateDirectoryTransacted function.
Syntax
Parameters
The path of the directory to use as a template when creating the new directory.
In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend «\?» to the path. For more information, see Naming a File.
The path of the directory to be created.
In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend «\?» to the path. For more information, see Naming a File.
A pointer to a SECURITY_ATTRIBUTES structure. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new directory.
If lpSecurityAttributes is NULL, the directory gets a default security descriptor. The access control lists (ACL) in the default security descriptor for a directory are inherited from its parent directory.
The target file system must support security on files and directories for this parameter to have an effect. This is indicated when GetVolumeInformation returns FS_PERSISTENT_ACLS.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero (0). To get extended error information, call GetLastError. Possible errors include the following.
Return code | Description |
---|---|
ERROR_ALREADY_EXISTS | The specified directory already exists. |
ERROR_PATH_NOT_FOUND | One or more intermediate directories do not exist. This function only creates the final directory in the path. To create all intermediate directories on the path, use the SHCreateDirectoryEx function. |
Remarks
The CreateDirectoryEx function allows you to create directories that inherit stream information from other directories. This function is useful, for example, when you are using Macintosh directories, which have a resource stream that is needed to properly identify directory contents as an attribute.
Some file systems, such as the NTFS file system, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent directory.
You can obtain a handle to a directory by calling the CreateFile function with the FILE_FLAG_BACKUP_SEMANTICS flag set. For a code example, see CreateFile.
To support inheritance functions that query the security descriptor of this object can heuristically determine and report that inheritance is in effect. For more information, see Automatic Propagation of Inheritable ACEs.
In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.
Technology | Supported |
---|---|
Server Message Block (SMB) 3.0 protocol | Yes |
SMB 3.0 Transparent Failover (TFO) | Yes |
SMB 3.0 with Scale-out File Shares (SO) | Yes |
Cluster Shared Volume File System (CsvFS) | Yes |
Resilient File System (ReFS) | Yes |
В
The winbase.h header defines CreateDirectoryEx as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.
mkdir mkdir
Создает каталог или подкаталог. Creates a directory or subdirectory. Расширения команд, включенные по умолчанию, позволяют использовать одну команду mkdir для создания промежуточных каталогов по указанному пути. Command extensions, which are enabled by default, allow you to use a single mkdir command to create intermediate directories in a specified path.
Эта команда аналогична команде MD. This command is the same as the md command.
Синтаксис Syntax
Параметры Parameters
Параметр Parameter | Описание Description |
---|---|
: : | Указывает диск, на котором нужно создать новый каталог. Specifies the drive on which you want to create the new directory. |
Указывает имя и расположение нового каталога. Specifies the name and location of the new directory. Максимальная длина любого отдельного пути определяется файловой системой. The maximum length of any single path is determined by the file system. Это обязательный параметр. This is a required parameter. | |
/? /? | Отображение справки в командной строке. Displays help at the command prompt. |
Примеры Examples
Чтобы создать каталог с именем Directory1 в текущем каталоге, введите: To create a directory named Directory1 within the current directory, type:
Чтобы создать дерево каталогов таксес\проперти\куррент в корневом каталоге с включенными расширениями команд, введите: To create the directory tree Taxes\Property\Current within the root directory, with command extensions enabled, type:
Чтобы создать дерево каталогов таксес\проперти\куррент в корневом каталоге, как в предыдущем примере, но при отключенных расширениях команд введите следующую последовательность команд: To create the directory tree Taxes\Property\Current within the root directory as in the previous example, but with command extensions disabled, type the following sequence of commands:
Creating an Application Directory Partition
An application directory partition is represented by a domainDNS object with an instanceType attribute value of DS_INSTANCETYPE_IS_NC_HEAD combined with DS_INSTANCETYPE_NC_IS_WRITEABLE. This domainDNS object represents the application directory partition root (NC head), and is named similar to a regular domain partition, for example, «DC=dynamicdata,DC=fabrikam,DC=com», which corresponds to a DNS name of «dynamicdata.fabrikam.com». An application directory partition can, therefore, be instantiated anywhere a domain partition can be instantiated. There is no NetBIOS name associated with an application directory partition.
It is possible to nest application directory partitions, that is, an application directory partition can have child application directory partitions. Searches with subtree scope rooted at an application directory partition head will generate continuation references to the child application directory partitions.
An application directory partition replica can only be created on a domain controller that is running on Windows Server 2003 and later and only while the Domain-Naming FSMO role is held by a Windows Server 2003 and later domain controller. In a mixed forest that has both Windows Server 2003 domain controllers and down-level domain controllers (WindowsВ 2000 domain controllers or Windows NT 4.0 primary domain controllers), an attempt to create an application directory partition replica on a down-level domain controller will fail.
An application directory partition also has a corresponding crossRef object in the Partitions container of the configuration partition. The crossRef can be pre-created manually before creating the domainDNS object. The pre-created crossRef object must have the attribute values shown in the following table or the partition creation will fail. If the crossRef object does not exist, the Active Directory server will create one when the application directory partition is created.
Attribute | Description |
---|---|
dnsRoot | Contains the DNS path of the domain controller that the application directory partition will be created on. |
Enabled | Contains FALSE. |
nCName | Contains the distinguished name of the partition. In the example above, this attribute would contain «DC=dynamicdata,DC=mydomain,DC=com». |
To create a new application directory partition with its first replica, perform the following steps
Bind to the namespace for the new partition, specifying the domain controller that will host the application directory partition in the ADsPath. For example, to create a partition with an ADsPath of «DC=dynamicdata,DC=mydomain,DC=com», the binding ADsPath would be «LDAP:///DC=mydomain,DC=com», where » » is the DNS name of the domain controller that will host the partition.
The bind operation must specify the fast and delegation options. The fast option allows the bind to succeed even if the namespace does not exist. The delegation option is required to allow the domain controller to contact the Domain-Naming FSMO role holder using the same credentials.
The system version of the domain controller must be Windows Server 2003 operating system and later.
Create a domainDNS object with an appropriate name for the partition, for example, «DC=dynamicdata», to represent the naming context head for the new partition. The domainDNS object must have an instanceType attribute with a value of 5 (DS_INSTANCETYPE_IS_NC_HEAD | DS_INSTANCETYPE_NC_IS_WRITEABLE). The instanceType attribute can only be set at creation time because it is a system-only attribute.
When the domainDNS object is created, the Active Directory server will perform the following steps:
Searches for a crossRef object in the Partitions container that has an nCName attribute value that matches the distinguished name of the partition and, if a match is found, modifies the crossRef object to represent the application directory partition. If a matching crossRef object is not found, the Active Directory server creates a new crossRef object to represent the application directory partition.
The following table lists important attributes of the crossRef object.
Attribute | Description |
---|---|
nCName | Contains the distinguished name of the partition. |
dnsRoot | Contains the DNS name of the partition. |
msDS-NC-Replica-Locations | The distinguished name of the nTDSDSA object of the domain controller for the first replica is added to this attribute. |
Initiate a synchronization of the configuration partition and wait for completion. This enables the client application to modify configuration parameters for the newly created application directory partition while bound to the same domain controller used for creating the application directory partition.
Create the domainDNS object with the DS_INSTANCETYPE_IS_NC_HEAD and DS_INSTANCETYPE_NC_IS_WRITEABLE flags set on the instanceType property. The instanceType property may contain other, private flags as well.
Populate the ms-DS-Has-Master-NCs attribute of the nTDSDSA object for the target domain controller with the distinguished name of the newly created application directory partition.
When the application directory partition is created, or when a new replica of the application directory partition is added and fully synchronized, the Active Directory server correctly registers the replica with NetLogon and DNS. For more information, and a list of the registered SRV records, see Locating an Application Directory Partition Host Server.
For more information about creating an application directory partition, see Example Code for Creating an Application Directory Partition.
Locating the Partitions Container
The distinguished name of the Partitions container can be found in one of two ways. The first is more complicated to perform, but will always provide an accurate result:
- Bind to RootDSE and obtain the configurationNamingContext attribute.
- Use the configurationNamingContext attribute to bind to the configuration container.
- Search in the configuration container for an object that is of the crossRefContainer type.
- Obtain the distinguishedName attribute value of the crossRefContainer object. This will be the distinguished name of the Partitions container.
For more information and a code example that shows this method for locating the Partitions container, see the GetPartitionsDNSearch function in Example Code for Locating the Partitions Container.
The second method is easier to implement, but relies on the Partitions container having a particular relative distinguished name. It is not currently possible to change the name of the Partitions container, but if this capability is added in the future, the procedure below will not work correctly if the Partitions container has been renamed.
- Bind to RootDSE and obtain the configurationNamingContext attribute.
- Combine the string «CN=Partitions,» followed by the configurationNamingContext attribute to form the distinguished name of the Partitions container. The distinguished name will be in the form «CN=Partitions,».
For more information and a code example that shows this method for locating the Partitions container, see the GetPartitionsDNManual function in Example Code for Locating the Partitions Container.