导出硬盘所有文件名到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

相关文章

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

linux下多个硬盘划分到同一挂载点问题

《linux下多个硬盘划分到同一挂载点问题》在Linux系统中,将多个硬盘划分到同一挂载点需要通过逻辑卷管理(LVM)来实现,首先,需要将物理存储设备(如硬盘分区)创建为物理卷,然后,将这些物理卷组成... 目录linux下多个硬盘划分到同一挂载点需要明确的几个概念硬盘插上默认的是非lvm总结Linux下多

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

Java下载文件中文文件名乱码的解决方案(文件名包含很多%)

《Java下载文件中文文件名乱码的解决方案(文件名包含很多%)》Java下载文件时,文件名中文乱码问题通常是由于编码不正确导致的,使用`URLEncoder.encode(filepath,UTF-8... 目录Java下载文件中文文件名乱码问题一般情况下,大家都是这样为了解决这个问题最终解决总结Java下

使用Navicat工具比对两个数据库所有表结构的差异案例详解

《使用Navicat工具比对两个数据库所有表结构的差异案例详解》:本文主要介绍如何使用Navicat工具对比两个数据库test_old和test_new,并生成相应的DDLSQL语句,以便将te... 目录概要案例一、如图两个数据库test_old和test_new进行比较:二、开始比较总结概要公司存在多

C#比较两个List集合内容是否相同的几种方法

《C#比较两个List集合内容是否相同的几种方法》本文详细介绍了在C#中比较两个List集合内容是否相同的方法,包括非自定义类和自定义类的元素比较,对于非自定义类,可以使用SequenceEqual、... 目录 一、非自定义类的元素比较1. 使用 SequenceEqual 方法(顺序和内容都相等)2.

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

Java导出Excel动态表头的示例详解

《Java导出Excel动态表头的示例详解》这篇文章主要为大家详细介绍了Java导出Excel动态表头的相关知识,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录前言一、效果展示二、代码实现1.固定头实体类2.动态头实现3.导出动态头前言本文只记录大致思路以及做法,代码不进

C#从XmlDocument提取完整字符串的方法

《C#从XmlDocument提取完整字符串的方法》文章介绍了两种生成格式化XML字符串的方法,方法一使用`XmlDocument`的`OuterXml`属性,但输出的XML字符串不带格式,可读性差,... 方法1:通过XMLDocument的OuterXml属性,见XmlDocument类该方法获得的xm

C#多线程编程中导致死锁的常见陷阱和避免方法

《C#多线程编程中导致死锁的常见陷阱和避免方法》在C#多线程编程中,死锁(Deadlock)是一种常见的、令人头疼的错误,死锁通常发生在多个线程试图获取多个资源的锁时,导致相互等待对方释放资源,最终形... 目录引言1. 什么是死锁?死锁的典型条件:2. 导致死锁的常见原因2.1 锁的顺序问题错误示例:不同