导出硬盘所有文件名到txt文本文件——C#学习笔记

news2024/9/22 8:20:53

下面的示例演示如何使用递归遍历目录树。递归方法很简洁,但如果目录树很大且嵌套很深,则有可能会引起堆栈溢出异常。

对于所处理的特定异常以及在每个文件和文件夹上执行的特定操作,都只是作为示例提供。您应该修改此代码来满足自己特定的需要。有关更多信息,请参见代码中的注释。

如下图所示:

 附代码如下:

using System;

namespace 创建人族
{
    public class RecursiveFileSearch
    {
        static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();

        static void Main()
        {
            // Start with drives if you have to search the entire computer.
            string[] drives = System.Environment.GetLogicalDrives();

            foreach (string dr in drives)
            {//去掉这个if循环,那么输出电脑所有硬盘文件名
                //将d改成你需要查询的目录
                if (dr.ToLowerInvariant().Contains("d") ) { 
                System.IO.DriveInfo di = new System.IO.DriveInfo(dr);

                // Here we skip the drive if it is not ready to be read. This
                // is not necessarily the appropriate action in all scenarios.
                if (!di.IsReady)
                {
                    Console.WriteLine("The drive {0} could not be read", di.Name);
                    System.IO.File.WriteAllText("C:\\Users\\Administrator\\Desktop\\1.txt", "The drive {0} could not be read");
                    continue;
                }
                System.IO.DirectoryInfo rootDir = di.RootDirectory;
                WalkDirectoryTree(rootDir);
                }
            }

            // Write out all the files that could not be processed.
            Console.WriteLine("Files with restricted access:");
            foreach (string s in log)
            {
                Console.WriteLine(s);
                System.IO.File.WriteAllText("C:\\Users\\Administrator\\Desktop\\1.txt", s);
            }
            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        static void WalkDirectoryTree(System.IO.DirectoryInfo root)
        {
            System.IO.FileInfo[] files = null;
            System.IO.DirectoryInfo[] subDirs = null;

            // First, process all the files directly under this folder
            try
            {//查找你需要的文件类型,这里是所有类型
                files = root.GetFiles("*.*");
            }
            // This is thrown if even one of the files requires permissions greater
            // than the application provides.
            catch (UnauthorizedAccessException e)
            {
                // This code just writes out the message and continues to recurse.
                // You may decide to do something different here. For example, you
                // can try to elevate your privileges and access the file again.
                log.Add(e.Message);
            }

            catch (System.IO.DirectoryNotFoundException e)
            {
                Console.WriteLine(e.Message);
                System.IO.File.WriteAllText("C:\\Users\\Administrator\\Desktop\\1.txt", e.Message);
            }

            if (files != null)
            {
                foreach (System.IO.FileInfo fi in files)
                {
                    // In this example, we only access the existing FileInfo object. If we
                    // want to open, delete or modify the file, then
                    // a try-catch block is required here to handle the case
                    // where the file has been deleted since the call to TraverseTree().
                    Console.WriteLine(fi.FullName);
                    //System.IO.File.AppendAllText ("C:\\Users\\Administrator\\Desktop\\1.txt", fi.FullName);
                    System.IO.File.AppendAllText("C:\\Users\\Administrator\\Desktop\\1.txt", fi.FullName + "\n");
                }

                // Now find all the subdirectories under this directory.
                subDirs = root.GetDirectories();

                foreach (System.IO.DirectoryInfo dirInfo in subDirs)
                {
                    // Resursive call for each subdirectory.
                    WalkDirectoryTree(dirInfo);
                }
            }
        }
    }




}

下面的示例演示在不使用递归的情况下如何循环访问目录树中的文件和文件夹。该技术使用泛型 Stack<(Of <(T>)>) 集合类型,该类型是一个后进先出 (LIFO) 堆栈。

对于所处理的特定异常以及在每个文件和文件夹上执行的特定操作,都只是作为示例提供。您应该修改此代码来满足自己特定的需要。有关更多信息,请参见代码中的注释。

using System;
using System.Collections.Generic;

namespace myns 
{
    public class StackBasedIteration
    {
        static void Main(string[] args)
        {
            // Specify the starting folder on the command line, or in 
            // Visual Studio in the Project > Properties > Debug pane.
            TraverseTree("G:\\");

            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        public static void TraverseTree(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack<string> dirs = new Stack<string>(20);

            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException();
            }
            dirs.Push(root);

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file. It may or may not be acceptable 
                // to ignore the exception and continue enumerating the remaining files and 
                // folders. It is also possible (but unlikely) that a DirectoryNotFound exception 
                // will be raised. This will happen if currentDir has been deleted by
                // another application or thread after our call to Directory.Exists. The 
                // choice of which exceptions to catch depends entirely on the specific task 
                // you are intending to perform and also on how much you know with certainty 
                // about the systems on which this code will run.
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(currentDir);
                }

                catch (UnauthorizedAccessException e)
                {

                    Console.WriteLine(e.Message);
                    continue;
                }

                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    try
                    {
                        // Perform whatever action is required in your scenario.
                        System.IO.FileInfo fi = new System.IO.FileInfo(file);
                        Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // If file was deleted by a separate application
                        //  or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }

                // Push the subdirectories onto the stack for traversal.
                // This could also be done before handing the files.
                foreach (string str in subDirs)
                    dirs.Push(str);
            }
        }
    }




}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2106040.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分类学习器(Classification Learner App)MATLAB

在MATLAB中&#xff0c;分类学习器用于构建和评估分类模型。MATLAB提供了一些工具和功能&#xff0c;帮助你进行分类任务&#xff0c;例如分类学习器应用程序、统计和机器学习工具箱中的函数等。 导入数据 我们在打开应用程序之前的第一步将是导入我们将在工作区使用的数据。…

新品上市丨科学级新款制冷相机sM4040A/sM4040B

sM4040B科学级显微制冷相机 特性 sM4040B搭载了 GSENSE4040BSI 3.2 英寸图像传感器&#xff0c;针对传感器固有的热噪声&#xff0c;专门设计了高效制冷模块&#xff0c;使得相机传感器的工作温度比环境温度低达 35-40 度。针对制冷相机常见的低温结雾现象设计了防结雾机制&a…

Serverless 应用引擎 SAE 助力袋拉拉研发提效 70%

作者&#xff1a;百潼 医院环保 IOT 设备的引领者&#xff1a;机汽猫 机汽猫是⼀家致⼒于通过投放⾃助取袋设备&#xff0c;为医院场景提供新型环保袋交付⽅式的科技公司。它成⽴于 2019 年&#xff0c;旗下品牌袋拉拉&#xff08;DaiLala&#xff09;通过投放⾃助取袋机&…

《Cloud Native Data Center Networking》(云原生数据中心网络设计)读书笔记 -- 10数据中心中的BGP

本章解答以下问题&#xff1a; ASN&#xff0c;团体&#xff08;community&#xff09;&#xff0c;属性&#xff08;attribute&#xff09;&#xff0c;最佳路径这些BGP术语是什么疑似&#xff1f;在数据中心中应该使用eBGP还是iBGP?在数据中心使用BGP时&#xff0c;应采用什…

序列化和反序列化之Serializable与Parcelable的异同

目录 序列化和反序列化Serializable 和 Parcelable 的区别Serializable特点Parcelable特点Serializable、Parcelable 使用场景区别总结 在 Android 开发中&#xff0c;序列化和反序列化是将对象转换为字节流以及从字节流还原对象的过程。Java 提供了 Serializable 接口&#xf…

jmeter中响应时间、TPS、服务器资源图表

一、响应时间图表 jmeter中的聚合报告已经足够显示响应时间&#xff0c;但是不会显示很详细&#xff0c;下面使用监听器中的插件查看&#xff0c; 添加后&#xff0c;可以不用更改任何配置&#xff0c;直接使用默认即可统计响应时间 还是抓取百度1分钟查看数据&#xff0c;也是…

Meta:大语言模型可以通过自我批判取得大幅提升!

夕小瑶科技说 原创 作者 | 谢年年 论文的审稿模式想必大家都不会陌生&#xff0c;一篇论文除了分配多个评审&#xff0c;最后还将由PC综合评估各位审稿人的reviews撰写meta-review。 最近&#xff0c;来自Meta的研究团队将这一模式引进到大模型的对齐训练中。模型同时扮演 执…

一. 从Hive开始

1. 怎么理解Hive Hive不能理解成一个传统意义上的数据库&#xff0c;应该理解成一个解决方案。 是Hadoop在hdfs和mapreduce之后才出现的一个结构化数据处理的解决方案。 Hdfs解决了大数据的存储问题&#xff0c;mapreduce解决了数据的计算问题。 一切似乎很美好。 但是使用成本…

人机环境系统智能与Petri网

人机环境系统工程是一门新兴的交叉学科&#xff0c;它以人、机、环境为系统&#xff0c;研究系统整体的优化。而 Petri 网是一种用于描述和分析系统动态行为的图形化建模工具。 在人机环境系统中&#xff0c;智能体现在人、机、环境三个要素之间的相互作用和协同工作。人的智能…

【微信小程序】搭建项目步骤 + 引入Tdesign UI

目录 创建1个空文件夹&#xff0c;选择下图基础模板 开启/支持sass 创建公共style文件并引入 引入Tdesign UI: 1. 初始化&#xff1a; 2. 安装后&#xff0c;开发工具进行构建&#xff1a; 3. 修改 app.json 4. 使用 5. 自定义主题色 创建1个空文件夹&#xff0c;选择下…

map和set的使用和底层实现

嗨喽大家好&#xff0c;时隔许久阿鑫又给大家带来了新的博客&#xff0c;c进阶——map和set的使用和底层实现&#xff0c;下面让我们开始今天的学习吧&#xff01; map和set的使用和底层实现 1.set和multiset的使用 2.map和multimap的使用 3.底层结构 1.set和multiset的使…

基于FCM模糊聚类算法的图像分割matlab仿真

目录 1.算法运行效果图预览 2.算法运行软件版本 3.部分核心程序 4.算法理论概述 4.1 FCM算法原理 4.2 图像分割中的应用 5.算法完整程序工程 1.算法运行效果图预览 (完整程序运行后无水印) 2.算法运行软件版本 matlab2022a 3.部分核心程序 &#xff08;完整版代码包…

单列表集合顶层接口Collection

List&#xff1a;添加元素是有序&#xff0c;可重复&#xff0c;有索引 Set&#xff1a;添加元素是无序&#xff0c;不重复&#xff0c;无索引 Collection是单列集合的祖宗接口&#xff0c;它的功能是全部单列集合都可以继承使用。 1.添加元素 细节1:如果我们要往List系列集…

ArcGIS出图格网小数位数设置

1、比如要去掉格网后面的小数点&#xff0c;如何设置呢&#xff1f; 2、如下图设置。

《软件工程导论》(第6版)第12章 面向对象实现 复习笔记

第12章 面向对象实现 一、面向对象实现概述 1&#xff0e;主要任务 &#xff08;1&#xff09;把面向对象设计结果翻译成用某种程序语言书写的面向对象程序。 &#xff08;2&#xff09;测试并调试面向对象的程序。 2&#xff0e;面向对象程序质量的影响因素 &#xff0…

Redis Pub/Sub模式:分布式系统中的解耦利器

序言 Redis的发布订阅&#xff08;Pub/Sub&#xff09;是一种消息通信模式&#xff0c;允许发布者&#xff08;Publisher&#xff09;发送消息到频道&#xff08;Channel&#xff09;&#xff0c;而订阅者&#xff08;Subscriber&#xff09;可以订阅一个或多个频道来接收消息…

惠中科技光伏清洗剂:绿色清洁,高效发电的守护者

在当今全球能源转型的大背景下&#xff0c;光伏产业作为绿色能源的重要组成部分&#xff0c;正以前所未有的速度蓬勃发展。然而&#xff0c;光伏板长期暴露于户外环境&#xff0c;不可避免地会遭受灰尘、鸟粪、油污等污染物的侵袭&#xff0c;这些污染物如同阴影般覆盖在光伏板…

代码随想录Day 35|动态规划,二维dp数组,滚动数组,leetcode题目:416.分割等和子集

提示&#xff1a;DDU&#xff0c;供自己复习使用。欢迎大家前来讨论~ 文章目录 动态规划Part03一、 动态规划&#xff1a;01背包理论基础01 背包二维dp数组01背包 二、动态规划&#xff1a;01背包理论基础&#xff08;滚动数组&#xff09;思路一维dp数组&#xff08;滚动数组&…

echarts三维立体扇形图+三维立体环形图配置详解记录

先看效果&#xff0c;注&#xff1a;三维立体echarts比较吃性能&#xff0c;同一页面如果有多个三维图进行渲染&#xff0c;进行跳转时可呢能会对整体页面产生影响&#xff0c;具体解决方法可查看本人另一篇文章 多个echarts使用3D导致页面卡顿的解决办法 三维立体扇形图 三维…

c# Avalonia 架构开发跨平台应用

实现了一个计算器的应用&#xff0c;先看在不同平台的效果 windows11上 ubuntu上 统信UOS 上 麒麟 kylin v10 好了&#xff0c;先说一下问题&#xff0c;如果想一套代码在不同平台同时运行&#xff0c;里面调用的逻辑还是要分系统的&#xff0c;先分linux系统和windows系统&a…