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

server/2024/11/14 11:53:21/

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

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

如下图所示:

 附代码如下:

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);}}}}


http://www.ppmy.cn/server/112388.html

相关文章

基于JavaWeb开发的Java+SpringBoot+vue+element实现校园闲置物品交易网站

基于JavaWeb开发的JavaSpringBootvueelement实现校园闲置物品交易网站 &#x1f345; 作者主页 网顺技术团队 &#x1f345; 欢迎点赞 &#x1f44d; 收藏 ⭐留言 &#x1f4dd; &#x1f345; 文末获取源码联系方式 &#x1f4dd; &#x1f345; 查看下方微信号获取联系方式 承…

2024 年全国大学生数学建模竞赛(国赛)浅析

需要完整资料&#xff0c;请关注WX&#xff1a;“小何数模”&#xff01; &#xff08;需要完整B、C和E题资料请关注WX&#xff1a;“小何数模”&#xff0c;获取资料链接&#xff01;&#xff09; 本次万众瞩目的全国大学生数学建模赛题已正式出炉&#xff0c;无论是赛题难度…

AI模型:追求全能还是专精?

AI模型简介 人工智能&#xff08;AI&#xff09;模型是人工智能系统的核心&#xff0c;它们是经过训练的算法&#xff0c;能够执行特定的任务&#xff0c;如图像识别、自然语言处理、游戏玩法、预测分析等。AI模型的类型很多&#xff0c;可以根据其功能和应用场景进行分类。常…

VR虚拟驾驶未来发展_vr自动驾驶汽车所带来的改变

在自动驾驶汽车的基础上&#xff0c;VR虚拟现实技术的应用也让自动驾驶汽车更加智能化&#xff0c;能够实现更高级的驾驶体验&#xff0c;今天这篇文章就和大家一起探讨一下 VR虚拟驾驶未来发展的趋势&#xff0c;以及虚拟现实自动驾驶汽车所带来的几个改变。 一、VR 虚拟驾驶未…

vue 踩坑记录

本地开发没有cookie 解决方案 设置代理&#xff0c;并把changeOrigin设为true proxy的changeOrigin如果设置为false&#xff1a;请求头中host仍然是浏览器发送过来的host&#xff1b; 如果设置成true&#xff1a;发送请求头中host会设置成target。 允许axios请求携带cookie等凭…

Linux学习笔记(4)----Debian压力测试方法

使用命令行终端压力测试需要两个实用工具&#xff1a;s-tui和stress sudo apt install s-tui stress 安装完成后&#xff0c;在终端中启动 s-tui实用工具&#xff1a; s-tui 执行后如下图&#xff1a; 你可以使用鼠标或键盘箭头键浏览菜单&#xff0c;然后点击“压力选项(Str…

kaggle注册收不到验证码、插件如何下载安装

综合这三个来看&#xff0c; 1.插件下载用的大佬给的分享链接 2.下载好压缩包以后需要解压缩 Header Editor插件网盘下载安装教程 - 哔哩哔哩 (bilibili.com) 3.安装插件时没找到crx文件&#xff0c;在浏览器插件界面点击“加载解压缩的扩展” 4.复制网址到插件里&#xff…

[论文笔记]Dimensionality Reduction by Learning an Invariant Mapping

引言 今天带来一篇真正远古(2005年)论文的笔记,论文是Dimensionality Reduction by Learning an Invariant Mapping。 该论文中提出的对比损失(2.1节)可以用于训练嵌入模型。 为了简单,下文中以翻译的口吻记录,比如替换"作者"为"我们"。 降维涉及将一…