TempFile.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Drawing;
  3. using System.IO;
  4. namespace Aio1Ef.Packer.Common
  5. {
  6. internal class TempFile : IDisposable
  7. {
  8. private readonly string _filePath;
  9. private readonly bool _containsFileName;
  10. public string FilePath
  11. {
  12. get { return _filePath; }
  13. }
  14. public TempFile(byte[] data, string fileName = null)
  15. {
  16. if (data == null)
  17. {
  18. IsValid = false;
  19. return;
  20. }
  21. _filePath = Path.GetTempFileName();
  22. if (fileName != null)
  23. {
  24. File.Delete(_filePath);
  25. Directory.CreateDirectory(_filePath);
  26. _filePath = Path.Combine(_filePath, fileName);
  27. _containsFileName = true;
  28. }
  29. File.WriteAllBytes(_filePath, data);
  30. IsValid = true;
  31. }
  32. public bool IsValid { get; private set; }
  33. private static byte[] Icon2Bytes(Icon icon)
  34. {
  35. if (icon == null)
  36. return null;
  37. using (var ms = new MemoryStream())
  38. {
  39. icon.Save(ms);
  40. return ms.ToArray();
  41. }
  42. }
  43. public TempFile(Icon icon, string fileName = null)
  44. : this(Icon2Bytes(icon), fileName)
  45. {
  46. }
  47. public void Dispose()
  48. {
  49. if (IsValid == false)
  50. return;
  51. if (_containsFileName)
  52. Directory.Delete(Path.GetDirectoryName(_filePath), true);
  53. else
  54. File.Delete(_filePath);
  55. }
  56. }
  57. }