directory_content.dart 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'dart:io';
  2. class DirectoryStat {
  3. final int subDirectoryCount;
  4. final int size;
  5. final int fileCount;
  6. DirectoryStat(this.subDirectoryCount, this.size, this.fileCount);
  7. }
  8. Future<DirectoryStat> getDirectorySize(Directory directory) async {
  9. int size = 0;
  10. int subDirCount = 0;
  11. int fileCount = 0;
  12. if (await directory.exists()) {
  13. // Get a list of all the files and directories in the directory
  14. final List<FileSystemEntity> entities = directory.listSync();
  15. // Iterate through the list of entities and add the sizes of the files to the total size
  16. for (FileSystemEntity entity in entities) {
  17. if (entity is File) {
  18. size += (await File(entity.path).length());
  19. fileCount++;
  20. } else if (entity is Directory) {
  21. subDirCount++;
  22. // If the entity is a directory, recursively calculate its size
  23. final DirectoryStat subDirStat =
  24. await getDirectorySize(Directory(entity.path));
  25. size += subDirStat.size;
  26. subDirCount += subDirStat.subDirectoryCount;
  27. fileCount += subDirStat.fileCount;
  28. }
  29. }
  30. }
  31. return DirectoryStat(subDirCount, size, fileCount);
  32. }
  33. Future<void> deleteDirectoryContents(String directoryPath) async {
  34. // Mark variables as final if they don't need to be modified
  35. final directory = Directory(directoryPath);
  36. if (!(await directory.exists())) {
  37. return;
  38. }
  39. final contents = await directory.list().toList();
  40. // Iterate through the list and delete each file or directory
  41. for (final fileOrDirectory in contents) {
  42. await fileOrDirectory.delete();
  43. }
  44. }
  45. Future<int> getFileSize(String path) async {
  46. final file = File(path);
  47. return await file.exists() ? await file.length() : 0;
  48. }