CommonHelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace compdfkit_tools.Helper
  9. {
  10. public static class CommonHelper
  11. {
  12. /// <summary>
  13. /// Returns the file size based on the specified file path, with the smallest unit being bytes (B).
  14. /// </summary>
  15. /// <param name="filePath">The path to the file.</param>
  16. /// <returns>
  17. /// The calculated file size, with units in bytes (B), kilobytes (KB), megabytes (MB), or gigabytes (GB).
  18. /// </returns>
  19. public static string GetFileSize(string filePath)
  20. {
  21. FileInfo fileInfo = null;
  22. try
  23. {
  24. fileInfo = new FileInfo(filePath);
  25. }
  26. catch
  27. {
  28. return "0B";
  29. }
  30. if (fileInfo != null && fileInfo.Exists)
  31. {
  32. double fileSize = fileInfo.Length;
  33. if (fileSize > 1024)
  34. {
  35. fileSize = Math.Round(fileSize / 1024, 2);
  36. if (fileSize > 1024)
  37. {
  38. fileSize = Math.Round(fileSize / 1024, 2);
  39. if (fileSize > 1024)
  40. {
  41. fileSize = Math.Round(fileSize / 1024, 2);
  42. return fileSize + " GB";
  43. }
  44. else
  45. {
  46. return fileSize + " MB";
  47. }
  48. }
  49. else
  50. {
  51. return fileSize + " KB";
  52. }
  53. }
  54. else
  55. {
  56. return fileSize + " B";
  57. }
  58. }
  59. return "0B";
  60. }
  61. public static string GetFilePathOrEmpty()
  62. {
  63. string selectedFilePath = string.Empty;
  64. OpenFileDialog openFileDialog = new OpenFileDialog();
  65. openFileDialog.Filter = "PDF files (*.pdf)|*.pdf";
  66. if (openFileDialog.ShowDialog() == true)
  67. {
  68. selectedFilePath = openFileDialog.FileName;
  69. }
  70. return selectedFilePath;
  71. }
  72. }
  73. }