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