(1)获取文件的字节长度
代码如下:
11 /// <summary>
12 /// 获取文件大小
13 /// </summary>
14 /// <param name="sFullName"></param>
15 /// <returns></returns>
16 public static long GetFileSize(string sFullName)
17 {
18 long lSize = 0;
19 if (File.Exists(sFullName))
20 lSize = new FileInfo(sFullName).Length;
21 return lSize;
22 }
(2)将文件的字节长度转换为实际应用中的大小
代码如下:
23 /// <summary>
24 /// 计算文件大小函数(保留两位小数),Size为字节大小
25 /// </summary>
26 /// <param name="Size">初始文件大小</param>
27 /// <returns></returns>
28 public static string CountSize(long Size)
29 {
30 string m_strSize = "";
31 long FactSize = 0;
32 FactSize = Size;
33 if (FactSize < 1024.00)
34 m_strSize = FactSize.ToString("F2") + " Byte";
35 else if (FactSize >= 1024.00 && FactSize < 1048576)
36 m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
37 else if (FactSize >= 1048576 && FactSize < 1073741824)
38 m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
39 else if (FactSize >= 1073741824)
40 m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
41 return m_strSize;
42 }
(3)获取一个文件夹下匹配的所有文件的大小
代码如下:
43 /// <summary>
44 /// 获取一批文件的大小(代码来自网络,不理解sMask参数的作用,可以考虑删除并修改代码
45 /// </summary>
46 /// <param name="sFilePath">文件所在的路径</param>
47 /// <param name="sMask">文件名称含通配符</param>
48 /// <returns></returns>
49 public static long GetFilesSize(string sFilePath, string sMask)
50 {
51 long lSize = 0;
52 if (sMask.Trim() == "")
53 return lSize;
54 DirectoryInfo pDirectoryInfo = new DirectoryInfo(sFilePath);
55 if (pDirectoryInfo.Exists == false)
56 return lSize;
57 FileInfo[] pFileInfos = pDirectoryInfo.GetFiles(sMask, SearchOption.TopDirectoryOnly);
58 foreach (FileInfo e in pFileInfos)
59 {
60 lSize += GetFileSize(e.FullName);
61 }
62 return lSize;
63 }