This article is a mirror article of machine translation, please click here to jump to the original article.

View: 28002|Reply: 0

[ASP.NET] C# gets the number of files in the specified folder and all file sizes

[Copy link]
Posted on 4/3/2015 4:05:08 PM | | |
  1. public static float length = 0;//文件总大小
  2. public int dirNum = 0; //文件目录个数
  3. public int fileNum = 0; //文件个数
  4. //绑定文件大小
  5. public void binder()
  6. {
  7. string fileName = Server.MapPath("Dir/" + Session["UserName"].ToString());
  8. length = Convert.ToSingle(GetDirectoryLength(fileName));
  9. string size = "0";
  10. if (length < 1024)
  11. {
  12. size = string.Format("{0:N0}", length) + "B";
  13. }
  14. else if (length > 1024)
  15. {
  16. if (length < 1048576)
  17. {
  18. size = string.Format("{0:N1}", length / 1024) + "KB";
  19. }
  20. else
  21. {
  22. size = string.Format("{0:N2}", length / 1048576) + "MB";
  23. }
  24. }
  25. Response.Write(size);
  26. }

  27. //获取文件夹大小总和
  28. public long GetDirectoryLength(string dirPath)
  29. {
  30. //判断给定的路径是否存在,如果不存在则退出
  31. if (!Directory.Exists(dirPath))
  32. return 0;
  33. long len = 0; //目录文件大小总和

  34. //定义一个DirectoryInfo对象
  35. DirectoryInfo di = new DirectoryInfo(dirPath);

  36. //通过GetFiles方法,获取di目录中的所有文件的大小
  37. foreach (FileInfo fi in di.GetFiles())
  38. {
  39. len += fi.Length;
  40. }
  41. fileNum += di.GetFiles().Length;

  42. //获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
  43. DirectoryInfo[] dis = di.GetDirectories();

  44. dirNum += dis.Length;

  45. if (dis.Length > 0)
  46. {

  47. for (int i = 0; i < dis.Length; i++)
  48. {
  49. len += GetDirectoryLength(dis[i].FullName);
  50. }
  51. }
  52. return len;

  53. }
Copy code




Previous:Super dick! Android root-free hyperterminal
Next:The GridView header font under ASP.NET is not bolded
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com