【C#】C#获取文件夹下的所有文件
2021-04-01 17:24
标签:image exce append list etc div 缩进 try pat 1、获得当前运行程序的路径 2、获得该文件夹下的文件,返回类型为FileInfo 3、获得该文件夹下的子目录,返回类型为DirectoryInfo 4、获得文件夹名 5、获得文件夹完整的路径名 6、获取文件的Name和FullName ------------------------------------------------------ 【C#】C#获取文件夹下的所有文件 标签:image exce append list etc div 缩进 try pat 原文地址:https://www.cnblogs.com/willingtolove/p/9235353.html #基础知识
1 string rootPath = Directory.GetCurrentDirectory();
1 string path=@"X:\XXX\XX";
2 DirectoryInfo root = new DirectoryInfo(path);
3 FileInfo[] files=root.GetFiles();
1 string path=@"X:\XXX\XX";
2 DirectoryInfo root = new DirectoryInfo(path);
3 DirctoryInfo[] dics=root.GetDirectories();
1 string path=@"X:\XXX\XX";
2 DirectoryInfo root = new DirectoryInfo(path);
3 string dicName=root.Name;
1 string path=@"X:\XXX\XX";
2 DirectoryInfo root = new DirectoryInfo(path);
3 string dicName=root.FullName;
1 string path=@"X:\XXX\XX";
2 DirectoryInfo root = new DirectoryInfo(path);
3 foreach (FileInfo f in root.GetFiles())
4 {
5 string name=f.Name;
6 string fullName=f.FullName;
7 }
#只获取目录下一级的文件夹与文件
1 String path = @"X:\xxx\xxx";
2
3 //第一种方法
4 string[] files = Directory.GetFiles(path, "*.txt");
5
6 foreach (string file in files)
7 {
8 Console.WriteLine(file);
9 }
10
11 //第二种方法
12 DirectoryInfo folder = new DirectoryInfo(path);
13
14 foreach (FileInfo file in folder.GetFiles("*.txt"))
15 {
16 Console.WriteLine(file.FullName);
17 }
# 递归地输出当前运行程序所在的磁盘下的所有文件名和子目录名
1 static void Main(string[] args)
2 {
3 //获取当前程序所在的文件路径
4 String rootPath = Directory.GetCurrentDirectory();
5 string parentPath = Directory.GetParent(rootPath).FullName;//上级目录
6 string topPath = Directory.GetParent(parentPath).FullName;//上上级目录
7 StreamWriter sw = null;
8 try
9 {
10 //创建输出流,将得到文件名子目录名保存到txt中
11 sw = new StreamWriter(new FileStream("fileList.txt", FileMode.Append));
12 sw.WriteLine("根目录:" + topPath);
13 getDirectory(sw, topPath, 2);
14 }
15 catch (IOException e)
16 {
17 Console.WriteLine(e.Message);
18 }
19 finally
20 {
21 if (sw != null)
22 {
23 sw.Close();
24 Console.WriteLine("完成");
25 }
26 }
27
28 }
29
30 ///
上一篇:C#中字符串的操作