1# Obtaining and Accessing a User Directory 2<!--Kit: Core File Kit--> 3<!--Subsystem: FileManagement--> 4<!--Owner: @wangke25; @gsl_1234; @wuchengjun5--> 5<!--Designer: @gsl_1234; @wangke25--> 6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang--> 7<!--Adviser: @foryourself--> 8 9## Obtaining and Accessing a User Directory (ArkTS) 10 11You can use [ohos.file.environment](../reference/apis-core-file-kit/js-apis-file-environment.md) to allow a third-party application to access files in a user directory. 12 13 **Constraints** 14 - The device must have the SystemCapability.FileManagement.File.Environment.FolderObtain system capability. Currently, only 2-in-1 devices are supported. 15 ```ts 16 if (!canIUse('SystemCapability.FileManagement.File.Environment.FolderObtain')) { 17 console.error('this api is not supported on this device'); 18 return; 19 } 20 ``` 21 - The APIs for obtaining user directories do not verify the permissions for accessing the related user directories. To access the user directories, the caller must have the related permissions. If a third-party application needs to access a user directory, user authorization for access to the **Download**, **Documents**, or **Desktop** directory is required via a dialog box. For details, see [Requesting User Authorization](../security/AccessToken/request-user-authorization.md). 22 <!--RP1--> 23 ```json 24 "requestPermissions" : [ 25 "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", 26 "ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", 27 "ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", 28 ] 29 ``` 30 <!--RP1End--> 31 32### Example 33 341. Obtain a user directory. 35 36```ts 37import { BusinessError } from '@kit.BasicServicesKit'; 38import { Environment } from '@kit.CoreFileKit'; 39 40function getUserDirExample() { 41 try { 42 const downloadPath = Environment.getUserDownloadDir(); 43 console.info(`success to getUserDownloadDir: ${downloadPath}`); 44 const documentsPath = Environment.getUserDocumentDir(); 45 console.info(`success to getUserDocumentDir: ${documentsPath}`); 46 } catch (error) { 47 const err: BusinessError = error as BusinessError; 48 console.error(`failed to get user dir, Error code: ${err.code}, message: ${err.message}`); 49 } 50} 51``` 52 532. Access files in the **Download** directory. 54 55```ts 56import { BusinessError } from '@kit.BasicServicesKit'; 57import { Environment } from '@kit.CoreFileKit'; 58import { fileIo as fs } from '@kit.CoreFileKit'; 59import { common } from '@kit.AbilityKit'; 60 61// Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 62let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 63 64function readUserDownloadDirExample(context: common.UIAbilityContext) { 65 // Check whether the caller has the READ_WRITE_DOWNLOAD_DIRECTORY permission. If not, apply for the permission from the user. 66 try { 67 // Obtain the path to the Download directory. 68 const downloadPath = Environment.getUserDownloadDir(); 69 console.info(`success to getUserDownloadDir: ${downloadPath}`); 70 const dirPath = context.filesDir; 71 console.info(`success to get filesDir: ${dirPath}`); 72 // List the files in the Download directory and copy them to the sandbox directory. 73 let fileList: string[] = fs.listFileSync(downloadPath); 74 fileList.forEach((file, index) => { 75 console.info(`${downloadPath} ${index}: ${file}`); 76 fs.copyFileSync(`${downloadPath}/${file}`, `${dirPath}/${file}`); 77 }); 78 // List the files in the sandbox directory. 79 fileList = fs.listFileSync(dirPath); 80 fileList.forEach((file, index) => { 81 console.info(`${dirPath} ${index}: ${file}`); 82 }); 83 } catch (error) { 84 const err: BusinessError = error as BusinessError; 85 console.error(`Error code: ${err.code}, message: ${err.message}`); 86 } 87} 88``` 89 903. Save the file to the **Download** directory. 91 92```ts 93import { BusinessError } from '@kit.BasicServicesKit'; 94import { Environment } from '@kit.CoreFileKit'; 95import { fileIo as fs } from '@kit.CoreFileKit'; 96 97function writeUserDownloadDirExample() { 98// Check whether the caller has the READ_WRITE_DOWNLOAD_DIRECTORY permission. If not, apply for the permission from the user. 99 try { 100 // Obtain the path to the Download directory. 101 const downloadPath = Environment.getUserDownloadDir(); 102 console.info(`success to getUserDownloadDir: ${downloadPath}`); 103 // Save temp.txt to the Download directory. 104 const file = fs.openSync(`${downloadPath}/temp.txt`, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 105 fs.writeSync(file.fd, 'write a message'); 106 fs.closeSync(file); 107 } catch (error) { 108 const err: BusinessError = error as BusinessError; 109 console.error(`Error code: ${err.code}, message: ${err.message}`); 110 } 111} 112``` 113 114 115 116## Obtaining and Accessing a User Directory (C/C++) 117 118In addition to ArkTS APIs, you can use C/C++ APIs to allow a third-party application to obtain and access a user directory. For details about the APIs, see [Environment](../reference/apis-core-file-kit/capi-oh-environment-h.md). 119 120 **Constraints** 121 - The device must have SystemCapability.FileManagement.File.Environment.FolderObtain. 122 - If a third-party application needs to access a user directory, user authorization for access to the **Download**, **Documents**, or **Desktop** directory is required via a dialog box. For details, see [Requesting User Authorization](../security/AccessToken/request-user-authorization.md). 123 124### Available APIs 125 126For details about the APIs, see [API Reference](../reference/apis-core-file-kit/capi-oh-environment-h.md). 127 128| API | Description | 129| ------------------------------------------------------------------------ | ------------------------------ | 130| FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result) | Obtains the sandbox path of the **Download** directory. This API is available only for 2-in-1 devices.| 131| FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result) | Obtains the sandbox path of the **Desktop** directory. This API is available only for 2-in-1 devices. | 132| FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result) | Obtains the sandbox path of the **Documents** directory. This API is available only for 2-in-1 devices.| 133 134### How to Develop 135 136**Adding Dynamic Link Libraries** 137 138Add the following libraries to **CMakeLists.txt**. 139 140```txt 141target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) 142``` 143 144**Adding Header Files** 145 146```c++ 147#include <filemanagement/environment/oh_environment.h> 148#include <filemanagement/fileio/oh_fileio.h> 149#include <hilog/log.h> 150``` 151 1521. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** directory. The memory allocated by **malloc()** must be released using **free()**. <br>Example: 153 154```c++ 155#include <cstdlib> 156 157void GetUserDownloadDirExample() 158{ 159 char *downloadPath = nullptr; 160 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 161 if (ret == 0) { 162 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 163 free(downloadPath); 164 } else { 165 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 166 } 167} 168``` 169 1702. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the **Download** directory and view the files in it. <br>Example: 171 172```c++ 173#include <cstdlib> 174#include <dirent.h> 175 176void ScanUserDownloadDirPathExample() 177{ 178 // Obtain the Download path. 179 char *downloadPath = nullptr; 180 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 181 if (ret == 0) { 182 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 183 } else { 184 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 185 return; 186 } 187 // View the files in the Download directory. 188 struct dirent **namelist = nullptr; 189 int num = scandir(downloadPath, &namelist, nullptr, nullptr); 190 if (num < 0) { 191 free(downloadPath); 192 OH_LOG_ERROR(LOG_APP, "Failed to scan dir"); 193 return; 194 } 195 for (int i = 0; i < num; i++) { 196 OH_LOG_INFO(LOG_APP, "%{public}s", namelist[i]->d_name); 197 } 198 free(downloadPath); 199 for (int i = 0; i < num; i++) { 200 free(namelist[i]); 201 } 202 free(namelist); 203} 204``` 205 2063. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** directory and save **temp.txt** to this directory. <br>Example: 207 208```c++ 209#include <fstream> 210 211void WriteUserDownloadDirPathExample() 212{ 213 // Obtain the Download path. 214 char *downloadPath = nullptr; 215 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 216 if (ret == 0) { 217 OH_LOG_INFO(LOG_APP, "Download Path=%{public}s", downloadPath); 218 } else { 219 OH_LOG_ERROR(LOG_APP, "GetDownloadPath fail, error code is %{public}d", ret); 220 return; 221 } 222 // Save a file to the Download directory. 223 std::string filePath = std::string(downloadPath) + "/temp.txt"; 224 free(downloadPath); 225 226 std::ofstream outfile; 227 outfile.open(filePath.c_str()); 228 if (!outfile) { 229 OH_LOG_ERROR(LOG_APP, "Failed to open file"); 230 return; 231 } 232 std::string msg = "Write a message"; 233 outfile.write(msg.c_str(), sizeof(msg)); 234 outfile.close(); 235} 236``` 237