/// <summary> /// 遍历目录所有文件 /// </summary> /// <param name="directory">目录</param> /// <param name="searchPattern">要查找的文件(*.txt)</param> /// <returns></returns> public static FileInfo[] GetFileList(DirectoryInfo directory, string searchPattern) { FileInfo[] fis = new FileInfo[0]; DirectoryInfo[] directorys = directory.GetDirectories(); foreach (DirectoryInfo di in directorys) { FileInfo[] fiss = GetFileList(di,searchPattern); AddNewArray<FileInfo>(ref fis, fiss); } AddNewArray<FileInfo>(ref fis, directory.GetFiles(searchPattern)); return fis; } /// <summary> /// 遍历目录所有文件大小 /// </summary> /// <param name="directory">目录</param> /// <param name="searchPattern">要查找的文件(*.txt)</param> /// <param name="symbol">是否带符号</param> /// <returns></returns> public static string GetFileListLength(DirectoryInfo directory, string searchPattern, bool symbol) { int fileListLength = 0; foreach (FileInfo fi in GetFileList(directory, searchPattern)) { fileListLength += (int)fi.Length; } return getSizeType(fileListLength, symbol); } /// <summary> /// 合并数组 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="A"></param> /// <param name="B"></param> public static void AddNewArray<T>(ref T[] A, T[] B)//合并数组,运用了一个范型,具体作用见下文 { T[] A1; A1 = (T[])A.Clone(); A = new T[A1.GetLength(0) + B.GetLength(0)]; for (int i = 0; i < A1.GetLength(0); i++) { A[i] = A1[i]; } for (int i = 0; i < B.GetLength(0); i++) { A[i + A1.GetLength(0)] = B[i]; } } /// <summary> /// 格式化大小符号 /// </summary> /// <param name="fileSize"></param> /// <param name="symbol">是否带符号</param> /// <returns></returns> public static string getSizeType(int fileSize, bool symbol) { string fileInfo = "0B"; if (fileSize > 0) { if (fileSize / 1024 > 0) { if (fileSize / 1024 / 1024 > 0) { if (fileSize / 1024 / 1024 / 1024 > 0) { fileInfo = (fileSize / 1024.0 / 1024.0 / 1024.0).ToString("0.0") + (symbol ? " GB" : ""); } else { fileInfo = (fileSize / 1024.0 / 1024).ToString("0.0") + (symbol ? " MB" : ""); } } else { fileInfo = (fileSize / 1024.0).ToString("0.0") + (symbol ? " KB" : ""); } } else { fileInfo = fileSize + (symbol ? " B" : ""); } } return fileInfo; }