遍历文件夹和文件
DirectoryInfo TheFolder=new DirectoryInfo(folderFullName);
//遍历文件夹
foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories())
this.listBox1.Items.Add(NextFolder.Name);
//遍历文件
foreach(FileInfo NextFile in TheFolder.GetFiles())
this.listBox2.Items.Add(NextFile.Name);
获取目录下的文件和子目录(不递归目录,支持通配符查找)
DirectoryInfo.GetFiles();//获取目录中(不包含子目录)的文件,返回类型为FileInfo[]
DirectoryInfo.GetDirectories();//获取目录(不包含子目录)的子目录,返回类型为DirectoryInfo[]
DirectoryInfo.GetFileSystemInfos();//获取指定目录下(不包含子目录)的文件和子目录,返回类型为FileSystemInfo[]
获取指定文件信息
FileInfo.Exists;//获取指定文件是否存在 FileInfo.Name; //FileInfo.Extensioin:获取文件的名称和扩展名 FileInfo.FullName; //获取文件的全限定名称(完整路径) FileInfo.Directory; //获取文件所在目录,返回类型为DirectoryInfo FileInfo.DirectoryName; //获取文件所在目录的路径(完整路径) FileInfo.Length; //获取文件的大小(字节数) FileInfo.IsReadOnly; //获取文件是否只读 FileInfo.Attributes; //获取或设置指定文件的属性,返回类型为FileAttributes枚举,可以是多个值的组合 FileInfo.CreationTime; //获取文件的创建时间、访问时间、修改时间 FileInfo.LastAccessTime; //获取文件的访问时间 FileInfo.LastWriteTime; //获取文件的修改时间
复制文件夹下所有内容
/// <summary> /// string sourcePath = "C:\Users\username\Desktop\New folder"; /// string targetPath = "C:\Users\username\Desktop\New folder\Backup folder"; /// </summary> /// <param name="sourceDirectory"></param> /// <param name="targetDirectory"></param> public void directoryCopy(string sourceDirectory, string targetDirectory) { try { DirectoryInfo dir = new DirectoryInfo(sourceDirectory); // Get files and subdirectories under the directory (without subdirectories) FileSystemInfo[] fileinfo = dir.GetFileSystemInfos(); foreach (FileSystemInfo i in fileinfo) { if (i is DirectoryInfo) // Determine if the folder { if (!Directory.Exists(targetDirectory + "\" + i.Name)) { // Create a subfolder without this folder in the target directory Directory.CreateDirectory(targetDirectory + "\" + i.Name); } // Recursively copy subfolder directoryCopy(i.FullName, targetDirectory + "\" + i.Name); } else { // Copy file if is not a folder, true means that files with the same name can be overwritten File.Copy(i.FullName, targetDirectory + "\" + i.Name, true); } } } catch (Exception ex) { MessageBox.Show("error"); } }
获取文件夹大小
public static long GetDirectoryLength(string dirPath) { if (!Directory.Exists(dirPath)) return 0; long len = 0; DirectoryInfo di = new DirectoryInfo(dirPath); foreach (FileInfo fi in di.GetFiles()) { len += fi.Length; } DirectoryInfo[] dis = di.GetDirectories(); if (dis.Length > 0) { for (int i = 0; i < dis.Length; i++) { len += GetDirectoryLength(dis[i].FullName); } } return len; }