ShareDirectoryClient Class

A client to interact with a specific directory, although it may not yet exist.

For operations relating to a specific subdirectory or file in this share, the clients for those entities can also be retrieved using the get_subdirectory_client and get_file_client functions.

Inheritance
azure.storage.fileshare._shared.base_client_async.AsyncStorageAccountHostsMixin
ShareDirectoryClient
azure.storage.fileshare._directory_client.ShareDirectoryClient
ShareDirectoryClient

Constructor

ShareDirectoryClient(account_url: str, share_name: str, directory_path: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | AsyncTokenCredential | None = None, *, token_intent: Literal['backup'] | None = None, **kwargs: Any)

Parameters

Name Description
account_url
Required
str

The URI to the storage account. In order to create a client given the full URI to the directory, use the from_directory_url classmethod.

share_name
Required
str

The name of the share for the directory.

directory_path
Required
str

The directory path for the directory with which to interact. If specified, this value will override a directory value specified in the directory URL.

snapshot
str

An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot.

default value: None
credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential

  • except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key" should be the storage account key.
default value: None

Keyword-Only Parameters

Name Description
token_intent
Literal['backup']

Required when using TokenCredential for authentication and ignored for other forms of authentication. Specifies the intent for all requests when using TokenCredential authentication. Possible values are:

backup - Specifies requests are intended for backup/admin type operations, meaning that all file/directory ACLs are bypassed and full permissions are granted. User must also have required RBAC permission.

allow_trailing_dot

If true, the trailing dot will not be trimmed from the target URI.

allow_source_trailing_dot

If true, the trailing dot will not be trimmed from the source URI.

api_version
str

The Storage API version to use for requests. Default value is the most recent service version that is compatible with the current SDK. Setting to an older version may result in reduced feature compatibility.

New in version 12.1.0.

secondary_hostname
str

The hostname of the secondary endpoint.

max_range_size
int

The maximum range size used for a file upload. Defaults to 4*1024*1024.

audience
str

The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net.

Methods

close

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

close_all_handles

Close any open file handles.

This operation will block until the service has closed all open handles.

close_handle

Close an open file handle.

create_directory

Creates a new directory under the directory referenced by the client.

create_subdirectory

Creates a new subdirectory and returns a client to interact with the subdirectory.

delete_directory

Marks the directory for deletion. The directory is later deleted during garbage collection.

delete_file

Marks the specified file for deletion. The file is later deleted during garbage collection.

delete_subdirectory

Deletes a subdirectory.

exists

Returns True if a directory exists and returns False otherwise.

from_connection_string

Create ShareDirectoryClient from a Connection String.

from_directory_url

Create a ShareDirectoryClient from a directory url.

get_directory_properties

Returns all user-defined metadata and system properties for the specified directory. The data returned does not include the directory's list of files.

get_file_client

Get a client to interact with a specific file.

The file need not already exist.

get_subdirectory_client

Get a client to interact with a specific subdirectory.

The subdirectory need not already exist.

list_directories_and_files

Lists all the directories and files under the directory.

list_handles

Lists opened handles on a directory or a file under the directory.

rename_directory

Rename the source directory.

:paramtype file_attributes:~azure.storage.fileshare.NTFSAttributes or str :keyword file_creation_time:

Creation time for the directory.

:paramtype file_creation_time:~datetime.datetime or str :keyword file_last_write_time:

Last write time for the file.

:paramtype file_last_write_time:~datetime.datetime or str :keyword file_change_time:

Change time for the directory. If not specified, change time will be set to the current date/time.

New in version 12.8.0: This parameter was introduced in API version '2021-06-08'.

set_directory_metadata

Sets the metadata for the directory.

Each call to this operation replaces all existing metadata attached to the directory. To remove all metadata from the directory, call this operation with an empty metadata dict.

set_http_headers

Sets HTTP headers on the directory.

upload_file

Creates a new file in the directory and returns a ShareFileClient to interact with the file.

close

This method is to close the sockets opened by the client. It need not be used when using with a context manager.

async close()

close_all_handles

Close any open file handles.

This operation will block until the service has closed all open handles.

async close_all_handles(recursive: bool = False, **kwargs: Any) -> Dict[str, int]

Parameters

Name Description
recursive
Required

Boolean that specifies if operation should apply to the directory specified by the client, its files, its subdirectories and their files. Default value is False.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

close_handle

Close an open file handle.

async close_handle(handle: str | Handle, **kwargs: Any) -> Dict[str, int]

Parameters

Name Description
handle
Required
str or Handle

A specific handle to close.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

The number of handles closed (this may be 0 if the specified handle was not found) and the number of handles failed to close in a dict.

create_directory

Creates a new directory under the directory referenced by the client.

async create_directory(**kwargs: Any) -> Dict[str, Any]

Keyword-Only Parameters

Name Description
file_attributes

The file system attributes for files and directories. If not set, the default value would be "none" and the attributes will be set to "Archive". Here is an example for when the var type is str: 'Temporary|Archive'. file_attributes value is not case sensitive.

file_creation_time

Creation time for the directory. Default value: "now".

file_last_write_time

Last write time for the directory. Default value: "now".

file_permission
str

If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the file-permission or file-permission-key should be specified.

file_permission_key
str

Key of the permission to be set for the directory/file. Note: Only one of the file-permission or file-permission-key should be specified.

file_change_time

Change time for the directory. If not specified, change time will be set to the current date/time.

New in version 12.8.0: This parameter was introduced in API version '2021-06-08'.

metadata

Name-value pairs associated with the directory as metadata.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

Directory-updated property dict (Etag and last modified).

Examples

Creates a directory.


   await directory.create_directory()

create_subdirectory

Creates a new subdirectory and returns a client to interact with the subdirectory.

async create_subdirectory(directory_name: str, **kwargs) -> ShareDirectoryClient

Parameters

Name Description
directory_name
Required
str

The name of the subdirectory.

Keyword-Only Parameters

Name Description
metadata

Name-value pairs associated with the subdirectory as metadata.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

ShareDirectoryClient

Examples

Create a subdirectory.


   # Create the directory
   await parent_dir.create_directory()

   # Create a subdirectory
   subdir = await parent_dir.create_subdirectory("subdir")

delete_directory

Marks the directory for deletion. The directory is later deleted during garbage collection.

async delete_directory(**kwargs: Any) -> None

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

Examples

Deletes a directory.


   await directory.delete_directory()

delete_file

Marks the specified file for deletion. The file is later deleted during garbage collection.

async delete_file(file_name: str, **kwargs: Any | None) -> None

Parameters

Name Description
file_name
Required
str

The name of the file to delete.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

Examples

Delete a file in a directory.


   # Delete the file in the directory
   await directory.delete_file(file_name="sample")

delete_subdirectory

Deletes a subdirectory.

async delete_subdirectory(directory_name: str, **kwargs) -> None

Parameters

Name Description
directory_name
Required
str

The name of the subdirectory.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

Examples

Delete a subdirectory.


   await parent_dir.delete_subdirectory("subdir")

exists

Returns True if a directory exists and returns False otherwise.

async exists(**kwargs: Any) -> bool

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

True if the directory exists, False otherwise.

from_connection_string

Create ShareDirectoryClient from a Connection String.

from_connection_string(conn_str: str, share_name: str, directory_path: str, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) -> Self

Parameters

Name Description
conn_str
Required
str

A connection string to an Azure Storage account.

share_name
Required
str

The name of the share.

directory_path
Required
str

The directory path.

credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential

  • except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key" should be the storage account key.
default value: None

Keyword-Only Parameters

Name Description
audience
str

The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net.

Returns

Type Description

A directory client.

from_directory_url

Create a ShareDirectoryClient from a directory url.

from_directory_url(directory_url: str, snapshot: str | Dict[str, Any] | None = None, credential: str | Dict[str, str] | AzureNamedKeyCredential | AzureSasCredential | TokenCredential | None = None, **kwargs: Any) -> Self

Parameters

Name Description
directory_url
Required
str

The full URI to the directory.

snapshot
str

An optional share snapshot on which to operate. This can be the snapshot ID string or the response returned from create_snapshot.

default value: None
credential

The credentials with which to authenticate. This is optional if the account URL already has a SAS token. The value can be a SAS token string, an instance of a AzureSasCredential or AzureNamedKeyCredential from azure.core.credentials, an account shared access key, or an instance of a TokenCredentials class from azure.identity. If the resource URI already contains a SAS token, this will be ignored in favor of an explicit credential

  • except in the case of AzureSasCredential, where the conflicting SAS tokens will raise a ValueError. If using an instance of AzureNamedKeyCredential, "name" should be the storage account name, and "key" should be the storage account key.
default value: None

Keyword-Only Parameters

Name Description
audience
str

The audience to use when requesting tokens for Azure Active Directory authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net.

Returns

Type Description

A directory client.

get_directory_properties

Returns all user-defined metadata and system properties for the specified directory. The data returned does not include the directory's list of files.

async get_directory_properties(**kwargs: Any) -> DirectoryProperties

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

DirectoryProperties

get_file_client

Get a client to interact with a specific file.

The file need not already exist.

get_file_client(file_name: str, **kwargs: Any) -> ShareFileClient

Parameters

Name Description
file_name
Required
str

The name of the file.

Returns

Type Description

A File Client.

get_subdirectory_client

Get a client to interact with a specific subdirectory.

The subdirectory need not already exist.

get_subdirectory_client(directory_name: str, **kwargs: Any) -> ShareDirectoryClient

Parameters

Name Description
directory_name
Required
str

The name of the subdirectory.

Returns

Type Description

A Directory Client.

Examples

Gets the subdirectory client.


   # Get a directory client and create the directory
   parent = share.get_directory_client("dir1")
   await parent.create_directory()

   # Get a subdirectory client and create the subdirectory "dir1/dir2"
   subdirectory = parent.get_subdirectory_client("dir2")
   await subdirectory.create_directory()

list_directories_and_files

Lists all the directories and files under the directory.

list_directories_and_files(name_starts_with: str | None = None, **kwargs: Any) -> AsyncItemPaged

Parameters

Name Description
name_starts_with
Required
str

Filters the results to return only entities whose names begin with the specified prefix.

Keyword-Only Parameters

Name Description
include

Include this parameter to specify one or more datasets to include in the response. Possible str values are "timestamps", "Etag", "Attributes", "PermissionKey".

New in version 12.6.0.

This keyword argument was introduced in API version '2020-10-02'.

include_extended_info

If this is set to true, file id will be returned in listed results.

New in version 12.6.0.

This keyword argument was introduced in API version '2020-10-02'.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

An auto-paging iterable of dict-like DirectoryProperties and FileProperties

Examples

List directories and files.


   # List the directories and files under the parent directory
   my_list = []
   async for item in parent_dir.list_directories_and_files():
       my_list.append(item)
   print(my_list)

list_handles

Lists opened handles on a directory or a file under the directory.

list_handles(recursive: bool = False, **kwargs: Any) -> AsyncItemPaged[Handle]

Parameters

Name Description
recursive
Required

Boolean that specifies if operation should apply to the directory specified by the client, its files, its subdirectories and their files. Default value is False.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

An auto-paging iterable of Handle

rename_directory

Rename the source directory.

:paramtype file_attributes:~azure.storage.fileshare.NTFSAttributes or str :keyword file_creation_time:

Creation time for the directory.

:paramtype file_creation_time:~datetime.datetime or str :keyword file_last_write_time:

Last write time for the file.

:paramtype file_last_write_time:~datetime.datetime or str :keyword file_change_time:

Change time for the directory. If not specified, change time will be set to the current date/time.

New in version 12.8.0: This parameter was introduced in API version '2021-06-08'.

async rename_directory(new_name: str, **kwargs: Any) -> ShareDirectoryClient

Keyword-Only Parameters

Name Description
metadata

A name-value pair to associate with a file storage object.

destination_lease

Required if the destination file has an active lease. Value can be a ShareLeaseClient object or the lease ID as a string.

Returns

Type Description

The new Directory Client.

set_directory_metadata

Sets the metadata for the directory.

Each call to this operation replaces all existing metadata attached to the directory. To remove all metadata from the directory, call this operation with an empty metadata dict.

async set_directory_metadata(metadata: Dict[str, Any], **kwargs: Any) -> Dict[str, Any]

Parameters

Name Description
metadata
Required

Name-value pairs associated with the directory as metadata.

Keyword-Only Parameters

Name Description
timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

Directory-updated property dict (Etag and last modified).

set_http_headers

Sets HTTP headers on the directory.

async set_http_headers(file_attributes: str | NTFSAttributes = 'none', file_creation_time: str | datetime | None = 'preserve', file_last_write_time: str | datetime | None = 'preserve', file_permission: str | None = None, permission_key: str | None = None, **kwargs: Any) -> Dict[str, Any]

Parameters

Name Description
file_attributes
Required

The file system attributes for files and directories. If not set, indicates preservation of existing values. Here is an example for when the var type is str: 'Temporary|Archive'

file_creation_time
Required

Creation time for the file Default value: Preserve.

file_last_write_time
Required

Last write time for the file Default value: Preserve.

file_permission
Required
str

If specified the permission (security descriptor) shall be set for the directory/file. This header can be used if Permission size is <= 8KB, else x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

permission_key
Required
str

Key of the permission to be set for the directory/file. Note: Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified.

Keyword-Only Parameters

Name Description
file_change_time

Change time for the directory. If not specified, change time will be set to the current date/time.

New in version 12.8.0: This parameter was introduced in API version '2021-06-08'.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

Returns

Type Description

File-updated property dict (Etag and last modified).

upload_file

Creates a new file in the directory and returns a ShareFileClient to interact with the file.

async upload_file(file_name: str, data: bytes | str | Iterable | AsyncIterable | IO, length: int | None = None, **kwargs) -> ShareFileClient

Parameters

Name Description
file_name
Required
str

The name of the file.

data
Required

Content of the file.

length
Required
int

Length of the file in bytes. Specify its maximum size, up to 1 TiB.

Keyword-Only Parameters

Name Description
metadata

Name-value pairs associated with the file as metadata.

content_settings

ContentSettings object used to set file properties. Used to set content type, encoding, language, disposition, md5, and cache control.

validate_content

If true, calculates an MD5 hash for each range of the file. The storage service checks the hash of the content that has arrived with the hash that was sent. This is primarily valuable for detecting bitflips on the wire if using http instead of https as https (the default) will already validate. Note that this MD5 hash is not stored with the file.

max_concurrency
int

Maximum number of parallel connections to use.

progress_hook

An async callback to track the progress of a long running upload. The signature is function(current: int, total: Optional[int]) where current is the number of bytes transferred so far, and total is the size of the blob or None if the size is unknown.

timeout
int

Sets the server-side timeout for the operation in seconds. For more details see https://learn.microsoft.com/rest/api/storageservices/setting-timeouts-for-file-service-operations. This value is not tracked or validated on the client. To configure client-side network timesouts see here.

encoding
str

Defaults to UTF-8.

Returns

Type Description

ShareFileClient

Examples

Upload a file to a directory.


   # Upload a file to the directory
   with open(SOURCE_FILE, "rb") as source:
       await directory.upload_file(file_name="sample", data=source)

Attributes

api_version

The version of the Storage API used for requests.

location_mode

The location mode that the client is currently using.

By default this will be "primary". Options include "primary" and "secondary".

primary_endpoint

The full primary endpoint URL.

primary_hostname

The hostname of the primary endpoint.

secondary_endpoint

The full secondary endpoint URL if configured.

If not available a ValueError will be raised. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

Exceptions

Type Description

secondary_hostname

The hostname of the secondary endpoint.

If not available this will be None. To explicitly specify a secondary hostname, use the optional secondary_hostname keyword argument on instantiation.

url

The full endpoint URL to this entity, including SAS token if used.

This could be either the primary endpoint, or the secondary endpoint depending on the current location_mode. :returns: The full endpoint URL to this entity, including SAS token if used. :rtype: str