导出硬盘所有文件名到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#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

C#自动化实现检测并删除PDF文件中的空白页面

《C#自动化实现检测并删除PDF文件中的空白页面》PDF文档在日常工作和生活中扮演着重要的角色,本文将深入探讨如何使用C#编程语言,结合强大的PDF处理库,自动化地检测并删除PDF文件中的空白页面,感... 目录理解PDF空白页的定义与挑战引入Spire.PDF for .NET库核心实现:检测并删除空白页

C#利用Free Spire.XLS for .NET复制Excel工作表

《C#利用FreeSpire.XLSfor.NET复制Excel工作表》在日常的.NET开发中,我们经常需要操作Excel文件,本文将详细介绍C#如何使用FreeSpire.XLSfor.NET... 目录1. 环境准备2. 核心功能3. android示例代码3.1 在同一工作簿内复制工作表3.2 在不同

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

C#实现高性能拍照与水印添加功能完整方案

《C#实现高性能拍照与水印添加功能完整方案》在工业检测、质量追溯等应用场景中,经常需要对产品进行拍照并添加相关信息水印,本文将详细介绍如何使用C#实现一个高性能的拍照和水印添加功能,包含完整的代码实现... 目录1. 概述2. 功能架构设计3. 核心代码实现python3.1 主拍照方法3.2 安全HBIT

C#实现SHP文件读取与地图显示的完整教程

《C#实现SHP文件读取与地图显示的完整教程》在地理信息系统(GIS)开发中,SHP文件是一种常见的矢量数据格式,本文将详细介绍如何使用C#读取SHP文件并实现地图显示功能,包括坐标转换、图形渲染、平... 目录概述功能特点核心代码解析1. 文件读取与初始化2. 坐标转换3. 图形绘制4. 地图交互功能缩放

C#使用SendMessage实现进程间通信的示例代码

《C#使用SendMessage实现进程间通信的示例代码》在软件开发中,进程间通信(IPC)是关键技术之一,C#通过调用WindowsAPI的SendMessage函数实现这一功能,本文将通过实例介绍... 目录第一章:SendMessage的底层原理揭秘第二章:构建跨进程通信桥梁2.1 定义通信协议2.2