DeleteDirectoryAsync.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using XGame.Framework.Asyncs;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. namespace XGame.Framework.FileSystem
  5. {
  6. public class DeleteDirectoryAsync : Async, IDeleteDirectoryAsync
  7. {
  8. readonly string _fullDirectory;
  9. readonly bool _includeSelf;
  10. public DeleteDirectoryAsync(string fullDirectory, bool includeSelf)
  11. {
  12. _fullDirectory = fullDirectory;
  13. _includeSelf = includeSelf;
  14. }
  15. public void Start()
  16. {
  17. try
  18. {
  19. if (!Directory.Exists(_fullDirectory)) { Completed(); return; }
  20. Task.Factory.StartNew(ThreadRemoveDirectories);
  21. }
  22. catch (System.Exception e)
  23. {
  24. Exception = e;
  25. Completed();
  26. }
  27. }
  28. private void OnThreadCompleted(object context)
  29. {
  30. if (null != context) Exception = context as System.Exception;
  31. Completed();
  32. }
  33. private void ThreadRemoveDirectories()
  34. {
  35. try
  36. {
  37. if (RemoveDirectories(_fullDirectory, _includeSelf))
  38. ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, null);
  39. else
  40. ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, new System.Exception("CPlusPlusDirectoryDeleteAsync::ThreadRemoveDirectories fail.."));
  41. }
  42. catch (System.Exception e)
  43. {
  44. ThreadScheduler.ThreadSchedulers.RunOnMainThread(OnThreadCompleted, e);
  45. }
  46. }
  47. private bool RemoveDirectories(string fullDirectory, bool includeSelf)
  48. {
  49. if (includeSelf)
  50. Directory.Delete(fullDirectory);
  51. else
  52. {
  53. Directory.Delete(fullDirectory);
  54. Directory.CreateDirectory(fullDirectory);
  55. }
  56. return true;
  57. }
  58. }
  59. }