栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

C# 获取路径下所有文件夹名,文件名

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C# 获取路径下所有文件夹名,文件名

    static void Main(string[] args)
        {      
            string topPath = @"F:";
            StreamWriter sw = null;
            try
            {
                //创建输出流,将得到文件名子目录名保存到txt中
                sw = new StreamWriter(new FileStream("fileList.txt", FileMode.Append));
                sw.WriteLine("根目录:" + topPath);
                getDirectory(sw, topPath, 2);
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    Console.WriteLine("完成");
                }
            }
        }

        /// 
        /// 获得指定路径下所有文件名
        /// 
        /// 文件写入流
        /// 文件写入流
        /// 输出时的缩进量
        public static void getFileName(StreamWriter sw, string path, int indent)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (FileInfo f in root.GetFiles())
            {
                for (int i = 0; i < indent; i++)
                {
                    sw.Write("  ");
                }
                sw.WriteLine(f.Name);
            }
        }

        /// 
        /// 获得指定路径下所有子目录名
        /// 
        /// 文件写入流
        /// 文件夹路径
        /// 输出时的缩进量
        public static void getDirectory(StreamWriter sw, string path, int indent)
        {
            getFileName(sw, path, indent);
            DirectoryInfo root = new DirectoryInfo(path);
            foreach (DirectoryInfo d in root.GetDirectories())
            {
                for (int i = 0; i < indent; i++)
                {
                    sw.Write("  ");
                }
                sw.WriteLine("文件夹:" + d.Name);
                getDirectory(sw, d.FullName, indent + 2);
                sw.WriteLine();
            }
        }

运行结果如图:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/905490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号