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