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

本文主要是介绍导出硬盘所有文件名到txt文本文件——C#学习笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

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

如下图所示:

 附代码如下:

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 foldertry{//查找你需要的文件类型,这里是所有类型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);}}}}

这篇关于导出硬盘所有文件名到txt文本文件——C#学习笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1138390

相关文章

java中使用POI生成Excel并导出过程

《java中使用POI生成Excel并导出过程》:本文主要介绍java中使用POI生成Excel并导出过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求说明及实现方式需求完成通用代码版本1版本2结果展示type参数为atype参数为b总结注:本文章中代码均为

C#基础之委托详解(Delegate)

《C#基础之委托详解(Delegate)》:本文主要介绍C#基础之委托(Delegate),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 委托定义2. 委托实例化3. 多播委托(Multicast Delegates)4. 委托的用途事件处理回调函数LINQ

在C#中调用Python代码的两种实现方式

《在C#中调用Python代码的两种实现方式》:本文主要介绍在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C#调用python代码的方式1. 使用 Python.NET2. 使用外部进程调用 Python 脚本总结C#调

C#中的 StreamReader/StreamWriter 使用示例详解

《C#中的StreamReader/StreamWriter使用示例详解》在C#开发中,StreamReader和StreamWriter是处理文本文件的核心类,属于System.IO命名空间,本... 目录前言一、什么是 StreamReader 和 StreamWriter?1. 定义2. 特点3. 用

Python实现将MySQL中所有表的数据都导出为CSV文件并压缩

《Python实现将MySQL中所有表的数据都导出为CSV文件并压缩》这篇文章主要为大家详细介绍了如何使用Python将MySQL数据库中所有表的数据都导出为CSV文件到一个目录,并压缩为zip文件到... python将mysql数据库中所有表的数据都导出为CSV文件到一个目录,并压缩为zip文件到另一个

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件

Linux文件名修改方法大全

《Linux文件名修改方法大全》在Linux系统中,文件名修改是一个常见且重要的操作,文件名修改可以更好地管理文件和文件夹,使其更具可读性和有序性,本文将介绍三种在Linux系统下常用的文件名修改方法... 目录一、引言二、使用mv命令修改文件名三、使用rename命令修改文件名四、mv命令和rename命

Java导入、导出excel用法步骤保姆级教程(附封装好的工具类)

《Java导入、导出excel用法步骤保姆级教程(附封装好的工具类)》:本文主要介绍Java导入、导出excel的相关资料,讲解了使用Java和ApachePOI库将数据导出为Excel文件,包括... 目录前言一、引入Apache POI依赖二、用法&步骤2.1 创建Excel的元素2.3 样式和字体2.

如何使用C#串口通讯实现数据的发送和接收

《如何使用C#串口通讯实现数据的发送和接收》本文详细介绍了如何使用C#实现基于串口通讯的数据发送和接收,通过SerialPort类,我们可以轻松实现串口通讯,并结合事件机制实现数据的传递和处理,感兴趣... 目录1. 概述2. 关键技术点2.1 SerialPort类2.2 异步接收数据2.3 数据解析2.

C#原型模式之如何通过克隆对象来优化创建过程

《C#原型模式之如何通过克隆对象来优化创建过程》原型模式是一种创建型设计模式,通过克隆现有对象来创建新对象,避免重复的创建成本和复杂的初始化过程,它适用于对象创建过程复杂、需要大量相似对象或避免重复初... 目录什么是原型模式?原型模式的工作原理C#中如何实现原型模式?1. 定义原型接口2. 实现原型接口3