or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-clients.mddirectory-client.mdfile-client.mdindex.mdlease-client.mdmodels.mdsas-generation.mdservice-client.mdshare-client.md

directory-client.mddocs/

0

# ShareDirectoryClient - Directory Operations

1

2

The ShareDirectoryClient provides operations for managing directories within file shares, including creating and deleting directories, listing contents, managing metadata, and handling file operations within directories.

3

4

## Import and Initialization

5

6

```python { .api }

7

from azure.storage.fileshare import ShareDirectoryClient, ShareFileClient

8

from azure.core.credentials import AzureNamedKeyCredential

9

from typing import Optional, Union, Dict, Any, List, IO, AnyStr, Iterable

10

```

11

12

## Constructor

13

14

```python { .api }

15

class ShareDirectoryClient:

16

def __init__(

17

self,

18

account_url: str,

19

share_name: str,

20

directory_path: str,

21

snapshot: Optional[Union[Dict[str, Any], str]] = None,

22

credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,

23

*,

24

token_intent: Optional[Literal['backup']] = None,

25

**kwargs: Any

26

) -> None:

27

"""

28

Create a ShareDirectoryClient for a specific directory.

29

30

Parameters:

31

account_url: The URL to the file service endpoint

32

share_name: Name of the share containing the directory

33

directory_path: Path to the directory from share root

34

snapshot: Optional share snapshot identifier

35

credential: Authentication credential

36

token_intent: Specifies the intent for all requests when using TokenCredential authentication

37

**kwargs: Additional client configuration options

38

"""

39

```

40

41

## Class Methods

42

43

```python { .api }

44

@classmethod

45

def from_directory_url(

46

cls,

47

directory_url: str,

48

credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,

49

**kwargs: Any

50

) -> ShareDirectoryClient:

51

"""

52

Create ShareDirectoryClient from directory URL.

53

54

Parameters:

55

directory_url: Complete URL to the directory

56

credential: Authentication credential

57

**kwargs: Additional client configuration options

58

59

Returns:

60

ShareDirectoryClient: Configured client instance

61

"""

62

63

@classmethod

64

def from_connection_string(

65

cls,

66

conn_str: str,

67

share_name: str,

68

directory_path: str,

69

credential: Optional[Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]] = None,

70

**kwargs: Any

71

) -> ShareDirectoryClient:

72

"""

73

Create ShareDirectoryClient from connection string.

74

75

Parameters:

76

conn_str: Azure Storage connection string

77

share_name: Name of the share

78

directory_path: Path to the directory from share root

79

credential: Optional credential to override connection string auth

80

**kwargs: Additional client configuration options

81

82

Returns:

83

ShareDirectoryClient: Configured client instance

84

"""

85

```

86

87

## Client Factory Methods

88

89

```python { .api }

90

def get_file_client(

91

self,

92

file_name: str,

93

**kwargs: Any

94

) -> ShareFileClient:

95

"""

96

Get a client to interact with a specific file in this directory.

97

98

Parameters:

99

file_name: Name of the file within this directory

100

101

Returns:

102

ShareFileClient: Client configured for the file

103

"""

104

105

def get_subdirectory_client(

106

self,

107

directory_name: str,

108

**kwargs: Any

109

) -> ShareDirectoryClient:

110

"""

111

Get a client to interact with a subdirectory.

112

113

Parameters:

114

directory_name: Name of the subdirectory within this directory

115

116

Returns:

117

ShareDirectoryClient: Client configured for the subdirectory

118

"""

119

```

120

121

## Directory Lifecycle Operations

122

123

```python { .api }

124

def create_directory(

125

self,

126

**kwargs: Any

127

) -> Dict[str, Any]:

128

"""

129

Creates a new directory under the share.

130

131

Parameters:

132

metadata: Dict of name-value pairs for directory metadata

133

file_attributes: File attributes for the directory (NTFSAttributes)

134

file_creation_time: Creation time for the file/directory

135

file_last_write_time: Last write time for the file/directory

136

file_permission: Security descriptor string or permission key

137

file_permission_key: Key for a previously created permission

138

timeout: Request timeout in seconds

139

140

Returns:

141

Dict containing directory creation response with ETag and properties

142

"""

143

144

def delete_directory(

145

self,

146

**kwargs: Any

147

) -> None:

148

"""

149

Marks the specified directory for deletion.

150

151

Parameters:

152

timeout: Request timeout in seconds

153

"""

154

155

def rename_directory(

156

self,

157

new_name: str,

158

**kwargs: Any

159

) -> ShareDirectoryClient:

160

"""

161

Rename a directory and return a client for the renamed directory.

162

163

Parameters:

164

new_name: New name for the directory

165

overwrite: Whether to overwrite existing directory with same name

166

ignore_readonly: Whether to ignore readonly attribute on destination

167

timeout: Request timeout in seconds

168

169

Returns:

170

ShareDirectoryClient: Client for the renamed directory

171

"""

172

173

def exists(

174

self,

175

**kwargs: Any

176

) -> bool:

177

"""

178

Returns True if the directory exists, False otherwise.

179

180

Parameters:

181

timeout: Request timeout in seconds

182

183

Returns:

184

bool: True if directory exists

185

"""

186

```

187

188

## Directory Content Management

189

190

```python { .api }

191

def list_directories_and_files(

192

self,

193

name_starts_with: Optional[str] = None,

194

marker: Optional[str] = None,

195

**kwargs: Any

196

) -> ItemPaged[Dict[str, Any]]:

197

"""

198

Lists all directories and files under this directory.

199

200

Parameters:

201

name_starts_with: Filter by name prefix

202

marker: Continuation token for pagination

203

results_per_page: Maximum items per page

204

timeout: Request timeout in seconds

205

206

Returns:

207

ItemPaged[Dict]: Paginated list of directory/file info dicts

208

209

Note:

210

Each dict contains:

211

- 'name': Name of the item

212

- 'is_directory': True for directories, False for files

213

- 'content_length': Size in bytes (files only)

214

- Additional properties for files and directories

215

"""

216

217

def create_subdirectory(

218

self,

219

directory_name: str,

220

**kwargs: Any

221

) -> ShareDirectoryClient:

222

"""

223

Creates a new subdirectory under this directory.

224

225

Parameters:

226

directory_name: Name of the subdirectory to create

227

metadata: Dict of name-value pairs for directory metadata

228

file_attributes: File attributes for the directory

229

file_creation_time: Creation time for the directory

230

file_last_write_time: Last write time for the directory

231

file_permission: Security descriptor string or permission key

232

timeout: Request timeout in seconds

233

234

Returns:

235

ShareDirectoryClient: Client for the newly created subdirectory

236

"""

237

238

def delete_subdirectory(

239

self,

240

directory_name: str,

241

**kwargs: Any

242

) -> None:

243

"""

244

Deletes a subdirectory under this directory.

245

246

Parameters:

247

directory_name: Name of the subdirectory to delete

248

timeout: Request timeout in seconds

249

"""

250

```

251

252

## File Operations

253

254

```python { .api }

255

def upload_file(

256

self,

257

file_name: str,

258

data: Union[bytes, str, Iterable[AnyStr], IO[AnyStr]],

259

length: Optional[int] = None,

260

**kwargs: Any

261

) -> ShareFileClient:

262

"""

263

Creates a new file in the directory and returns a ShareFileClient.

264

265

Parameters:

266

file_name: Name of the file to create

267

data: File content to upload

268

length: Length of the data in bytes (required for streams)

269

overwrite: Whether to overwrite existing file

270

max_concurrency: Number of parallel upload threads

271

content_settings: ContentSettings object with HTTP properties

272

metadata: Dict of name-value pairs for file metadata

273

validate_content: Whether to validate content with MD5 hash

274

timeout: Request timeout in seconds

275

276

Returns:

277

ShareFileClient: Client for the newly created file

278

"""

279

280

def delete_file(

281

self,

282

file_name: str,

283

**kwargs: Any

284

) -> None:

285

"""

286

Marks the specified file for deletion.

287

288

Parameters:

289

file_name: Name of the file to delete

290

timeout: Request timeout in seconds

291

"""

292

```

293

294

## Directory Properties and Metadata

295

296

```python { .api }

297

def get_directory_properties(

298

self,

299

**kwargs: Any

300

) -> DirectoryProperties:

301

"""

302

Returns all user-defined metadata and system properties for the directory.

303

304

Parameters:

305

timeout: Request timeout in seconds

306

307

Returns:

308

DirectoryProperties: Object containing all directory properties

309

"""

310

311

def set_directory_metadata(

312

self,

313

metadata: Dict[str, Any],

314

**kwargs: Any

315

) -> Dict[str, Any]:

316

"""

317

Sets user-defined metadata for the directory.

318

319

Parameters:

320

metadata: Dict of name-value pairs (keys must be valid metadata names)

321

timeout: Request timeout in seconds

322

323

Returns:

324

Dict containing response with ETag and last modified time

325

"""

326

327

def set_http_headers(

328

self,

329

**kwargs: Any

330

) -> Dict[str, Any]:

331

"""

332

Sets HTTP headers on the directory.

333

334

Parameters:

335

file_attributes: File attributes for the directory

336

file_creation_time: Creation time for the directory

337

file_last_write_time: Last write time for the directory

338

file_permission: Security descriptor string or permission key

339

file_permission_key: Key for a previously created permission

340

timeout: Request timeout in seconds

341

342

Returns:

343

Dict containing response with ETag and last modified time

344

"""

345

```

346

347

## Handle Management

348

349

```python { .api }

350

def list_handles(

351

self,

352

recursive: bool = False,

353

**kwargs: Any

354

) -> ItemPaged[Handle]:

355

"""

356

Lists handles for directory, subdirectories, and files.

357

358

Parameters:

359

recursive: Whether to list handles recursively in subdirectories

360

marker: Continuation token for pagination

361

results_per_page: Maximum handles per page

362

timeout: Request timeout in seconds

363

364

Returns:

365

ItemPaged[Handle]: Paginated list of open handles

366

"""

367

368

def close_handle(

369

self,

370

handle: Union[str, Handle],

371

**kwargs: Any

372

) -> Dict[str, int]:

373

"""

374

Closes an open file handle.

375

376

Parameters:

377

handle: Handle ID string or Handle object to close

378

timeout: Request timeout in seconds

379

380

Returns:

381

Dict containing number of handles closed

382

"""

383

384

def close_all_handles(

385

self,

386

recursive: bool = False,

387

**kwargs: Any

388

) -> Dict[str, int]:

389

"""

390

Closes all open file handles for the directory, subdirectories, and files.

391

392

Parameters:

393

recursive: Whether to close handles recursively in subdirectories

394

timeout: Request timeout in seconds

395

396

Returns:

397

Dict containing number of handles closed

398

"""

399

```

400

401

## Properties

402

403

```python { .api }

404

@property

405

def url(self) -> str:

406

"""The full endpoint URL to the directory."""

407

408

@property

409

def share_name(self) -> str:

410

"""The name of the share containing this directory."""

411

412

@property

413

def directory_path(self) -> str:

414

"""The path to the directory with which to interact."""

415

416

@property

417

def snapshot(self) -> Optional[str]:

418

"""An optional share snapshot on which to operate."""

419

420

@property

421

def account_name(self) -> str:

422

"""The storage account name."""

423

424

@property

425

def credential(self) -> Union[str, Dict[str, str], AzureNamedKeyCredential, AzureSasCredential, TokenCredential]:

426

"""The credential used to authenticate."""

427

```

428

429

## Usage Examples

430

431

### Basic Directory Operations

432

433

```python { .api }

434

from azure.storage.fileshare import ShareDirectoryClient

435

from azure.core.credentials import AzureNamedKeyCredential

436

437

# Initialize directory client

438

credential = AzureNamedKeyCredential("myaccount", "mykey")

439

directory_client = ShareDirectoryClient(

440

account_url="https://myaccount.file.core.windows.net",

441

share_name="documents",

442

directory_path="projects/2024",

443

credential=credential

444

)

445

446

# Check if directory exists

447

if not directory_client.exists():

448

# Create directory with metadata

449

directory_client.create_directory(

450

metadata={"created_by": "automation", "project": "data_migration"}

451

)

452

print("Directory created successfully")

453

else:

454

print("Directory already exists")

455

456

# Get directory properties

457

properties = directory_client.get_directory_properties()

458

print(f"Directory created: {properties.creation_time}")

459

print(f"Last modified: {properties.last_modified}")

460

print(f"Metadata: {properties.metadata}")

461

```

462

463

### Directory Content Management

464

465

```python { .api }

466

# List all contents

467

contents = list(directory_client.list_directories_and_files())

468

for item in contents:

469

item_type = "Directory" if item.get('is_directory') else "File"

470

size_info = f" ({item.get('content_length', 0)} bytes)" if not item.get('is_directory') else ""

471

print(f"{item_type}: {item['name']}{size_info}")

472

473

# Filter by prefix

474

reports = list(directory_client.list_directories_and_files(

475

name_starts_with="report_"

476

))

477

478

# Create subdirectories with different attributes

479

from azure.storage.fileshare import NTFSAttributes

480

from datetime import datetime

481

482

archive_dir = directory_client.create_subdirectory(

483

"archive",

484

metadata={"type": "archive", "retention": "7years"},

485

file_attributes=NTFSAttributes.Directory | NTFSAttributes.ReadOnly

486

)

487

488

temp_dir = directory_client.create_subdirectory(

489

"temp",

490

file_creation_time=datetime.utcnow()

491

)

492

```

493

494

### File Operations Within Directory

495

496

```python { .api }

497

from azure.storage.fileshare import ContentSettings

498

499

# Upload text file

500

text_content = "This is a sample document."

501

file_client = directory_client.upload_file(

502

file_name="readme.txt",

503

data=text_content.encode('utf-8'),

504

content_settings=ContentSettings(

505

content_type="text/plain",

506

content_encoding="utf-8"

507

),

508

metadata={"author": "system", "version": "1.0"}

509

)

510

511

# Upload binary file

512

with open("local_image.jpg", "rb") as image_data:

513

image_client = directory_client.upload_file(

514

file_name="image.jpg",

515

data=image_data,

516

content_settings=ContentSettings(content_type="image/jpeg"),

517

overwrite=True

518

)

519

520

# Get file client for existing file

521

existing_file = directory_client.get_file_client("config.json")

522

523

# Download file through directory client

524

config_data = existing_file.download_file().readall()

525

print(f"Downloaded {len(config_data)} bytes")

526

```

527

528

### Batch Operations

529

530

```python { .api }

531

# Upload multiple files

532

files_to_upload = [

533

("report1.pdf", "reports/monthly_report.pdf"),

534

("report2.pdf", "reports/quarterly_report.pdf"),

535

("summary.txt", "summaries/executive_summary.txt")

536

]

537

538

uploaded_clients = []

539

for file_name, local_path in files_to_upload:

540

with open(local_path, "rb") as file_data:

541

client = directory_client.upload_file(

542

file_name=file_name,

543

data=file_data,

544

overwrite=True

545

)

546

uploaded_clients.append(client)

547

print(f"Uploaded: {file_name}")

548

549

# Delete multiple files

550

files_to_delete = ["temp1.txt", "temp2.txt", "old_backup.zip"]

551

for file_name in files_to_delete:

552

try:

553

directory_client.delete_file(file_name)

554

print(f"Deleted: {file_name}")

555

except Exception as e:

556

print(f"Failed to delete {file_name}: {e}")

557

```

558

559

### Directory Tree Operations

560

561

```python { .api }

562

# Create nested directory structure

563

base_dirs = ["projects", "archives", "temp"]

564

sub_dirs = ["2024", "2023", "2022"]

565

566

for base_dir in base_dirs:

567

base_client = directory_client.create_subdirectory(base_dir)

568

for sub_dir in sub_dirs:

569

year_client = base_client.create_subdirectory(sub_dir)

570

print(f"Created: {base_dir}/{sub_dir}")

571

572

# Recursive content listing

573

def list_directory_tree(dir_client, prefix=""):

574

"""Recursively list directory contents."""

575

items = list(dir_client.list_directories_and_files())

576

for item in items:

577

print(f"{prefix}{item['name']}")

578

if item.get('is_directory'):

579

sub_client = dir_client.get_subdirectory_client(item['name'])

580

list_directory_tree(sub_client, prefix + " ")

581

582

print("Directory tree:")

583

list_directory_tree(directory_client)

584

```

585

586

### Handle Management

587

588

```python { .api }

589

# List open handles

590

handles = list(directory_client.list_handles(recursive=True))

591

print(f"Found {len(handles)} open handles")

592

593

for handle in handles:

594

print(f"Handle {handle.id}:")

595

print(f" Path: {handle.path}")

596

print(f" Client: {handle.client_name}")

597

print(f" Client IP: {handle.client_ip}")

598

print(f" Open time: {handle.open_time}")

599

print(f" Access rights: {handle.access_rights}")

600

601

# Close specific handle

602

if handles:

603

closed_count = directory_client.close_handle(handles[0])

604

print(f"Closed {closed_count['closed_handles_count']} handle(s)")

605

606

# Close all handles (useful for maintenance)

607

all_closed = directory_client.close_all_handles(recursive=True)

608

print(f"Closed {all_closed['closed_handles_count']} total handle(s)")

609

```

610

611

### Metadata and Properties Management

612

613

```python { .api }

614

from azure.storage.fileshare import NTFSAttributes

615

from datetime import datetime, timezone

616

617

# Update directory metadata

618

directory_client.set_directory_metadata({

619

"department": "engineering",

620

"project_code": "PROJ-2024-001",

621

"retention_policy": "5years",

622

"last_review": datetime.now(timezone.utc).isoformat()

623

})

624

625

# Set directory attributes and timestamps

626

directory_client.set_http_headers(

627

file_attributes=NTFSAttributes.Directory | NTFSAttributes.Archive,

628

file_creation_time=datetime(2024, 1, 1),

629

file_last_write_time=datetime.now(timezone.utc)

630

)

631

632

# Get updated properties

633

properties = directory_client.get_directory_properties()

634

print(f"Attributes: {properties.file_attributes}")

635

print(f"Creation time: {properties.creation_time}")

636

print(f"Last write time: {properties.last_write_time}")

637

print(f"Updated metadata: {properties.metadata}")

638

```

639

640

### Directory Renaming and Movement

641

642

```python { .api }

643

# Rename directory

644

try:

645

new_directory_client = directory_client.rename_directory(

646

new_name="projects_2024_archived",

647

overwrite=False # Fail if destination exists

648

)

649

print(f"Directory renamed to: {new_directory_client.directory_path}")

650

except Exception as e:

651

print(f"Rename failed: {e}")

652

653

# Move directory (rename with path change)

654

current_client = ShareDirectoryClient(

655

account_url="https://myaccount.file.core.windows.net",

656

share_name="documents",

657

directory_path="temp/project_a",

658

credential=credential

659

)

660

661

moved_client = current_client.rename_directory(

662

new_name="archive/completed/project_a"

663

)

664

print(f"Directory moved to: {moved_client.directory_path}")

665

```

666

667

### Error Handling and Validation

668

669

```python { .api }

670

from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError

671

672

# Safe directory creation

673

try:

674

directory_client.create_directory()

675

except ResourceExistsError:

676

print("Directory already exists, updating metadata...")

677

directory_client.set_directory_metadata({

678

"updated": datetime.now().isoformat()

679

})

680

681

# Validate before operations

682

if directory_client.exists():

683

properties = directory_client.get_directory_properties()

684

685

# Check if directory is empty before deletion

686

contents = list(directory_client.list_directories_and_files())

687

if not contents:

688

directory_client.delete_directory()

689

print("Empty directory deleted")

690

else:

691

print(f"Directory contains {len(contents)} items, skipping deletion")

692

else:

693

print("Directory does not exist")

694

695

# Handle file operation errors

696

try:

697

directory_client.delete_file("nonexistent.txt")

698

except ResourceNotFoundError:

699

print("File not found for deletion")

700

```

701

702

The ShareDirectoryClient provides comprehensive directory management capabilities, enabling you to create hierarchical folder structures, manage directory contents, handle file operations, and maintain directory metadata and properties efficiently.