目录

Deleting a File from a Specified Path

Use Cases

Enterprise Data Guard Kit allows apps to delete files from a specified path in the personal data directory of a user.

API Description

For details about these APIs, please refer to the API Reference.

API Description
deleteFile(path: string, callback: AsyncCallback<void>): void Deletes a file from a specified path using a callback.
deleteFile(path: string): Promise<void> Deletes a file from a specified path using a promise.

Development Procedure

  1. Import required modules.

    import { BusinessError } from '@kit.BasicServicesKit';
    import { fileGuard } from '@kit.EnterpriseDataGuardKit';
    import { hilog } from '@kit.PerformanceAnalysisKit';
  2. Initialize the guard object of FileGuard and call the deleteFile API to delete a file from the specified path.

    • Delete a file from a specified path by using a callback.

      const TAG: string = 'FileGuard_DeleteFile';
      const DOMAIN: number = 0x0000;
      
      /**
       * Delete a file from a specified path and return the result asynchronously using a callback.
       * @param accountId: user ID
       */
      function deleteFileCallback(accountId: number) {
        let guard: fileGuard.FileGuard = new fileGuard.FileGuard();
        let path: string = `/data/service/el2/${accountId}/hmdfs/account/files/Docs/Documents/ccc.txt`;
        guard.deleteFile(path, (err: BusinessError) => {
          if (err) {
            hilog.error(DOMAIN, TAG, `Failed to delete file. Code: ${err.code}, message: ${err.message}.`);
          } else {
            hilog.info(DOMAIN, TAG, `Succeeded in deleting file.`);
          }
        });
      }
    • Delete a file from a specified path using a promise.

      const TAG: string = 'FileGuard_DeleteFile';
      const DOMAIN: number = 0x0000;
      
      // ...
      /**
       * Delete a file from a specified path and return the result asynchronously using a promise.
       * @param accountId: user ID
       */
      function deleteFilePromise(accountId: number) {
        let guard: fileGuard.FileGuard = new fileGuard.FileGuard();
        let path: string = `/data/service/el2/${accountId}/hmdfs/account/files/Docs/Documents/ddd.txt`;
        guard.deleteFile(path).then(() => {
          hilog.info(DOMAIN, TAG, `Succeeded in deleting file.`);
        }).catch((err: BusinessError) => {
          hilog.error(DOMAIN, TAG, `Failed to delete file. Code: ${err.code}, message: ${err.message}.`);
        });
      }