C#读取文件夹中的文件操作浅析

本文介绍C#中如何读取文件夹内的文件,包括基本读取操作、递归查找子目录及其文件的方法,并提供实用代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C#读取文件夹中的文件操作浅析 C#读取文件夹中的文件操作是怎么样子的呢?那么本文就向你介绍这方面的内容,希望对你有所帮助。

C#读取文件夹的操作是如何进行的呢?首先让我们来看啊可能:读出一个文件夹中的所有文件(文件数从0个到N多不定).没有文件返回假.

都是ascii码文件.

读每个文件的前一部分至出现第一个 /s./s/r 为止.

读出来放后放至string[] filetsr中.


  1. strFiles=Directory.GetFiles(@"c:/Import");
  2. foreach(stringstrFileinstrFiles)
  3. {
  4. File.Move(strFile,strFile.Replace("Import","Rubbish_Files"));
  5. //上面这句换为你的C#读取文件夹处理。
  6. }

试试看C#读取文件夹的代码吧,没来得及调试,有问题自己改改吧!


  1. usingSystem;
  2. usingSystem.IO;
  3. classTest
  4. {
  5. publicstaticvoidMain()
  6. {
  7. try
  8. {
  9. //Onlygetfilesthatbeginwiththeletter"c."
  10. inti=0;
  11. string[]dirs=Directory.GetFiles(@"c:/","c*");
  12. Console.WriteLine("Thenumberoffilesstartingwithcis{0}.",dirs.Length);
  13. string[]filetsr=newString[dirs.Length];
  14. foreach(stringdirindirs)
  15. {
  16. FileStreamfs=newFileStream(dir,FileMode.Open);
  17. byte[]readBuf=newbyte[fs.Length];
  18. syncF.Read(readBuf,0,fs.Length);
  19. data=Encoding.ASCII.GetString(readBuf);
  20. if(data.IndexOf("/s./s/r")>-1)
  21. {
  22. i++;
  23. filestr[i]=Microsoft.Basic.Left(data.IndexOf("/s./s/r")-1)
  24. }
  25. }
  26. }
  27. catch(Exceptione)
  28. {
  29. Console.WriteLine("Theprocessfailed:{0}",e.ToString());
  30. }
  31. }
  32. }

C#中遍历文件夹目录的问题

C#读取文件夹之递归实现查找目录下的所有子目录和文件


  1. publicvoidFindFile(stringdir)//参数为指定的目录
  2. {
  3. //C#读取文件夹在指定目录及子目录下查找文件,在listBox1中列出子目录及文件
  4. DirectoryInfoDir=newDirectoryInfo(dir);
  5. try
  6. {
  7. foreach(DirectoryInfodinDir.GetDirectories())//查找子目录
  8. {
  9. FindFile(Dir+d.ToString()+"//");
  10. listBox1.Items.Add(Dir+d.ToString()+"//");//listBox1中填加目录名
  11. }
  12. foreach(FileInfofinDir.GetFiles("*.*"))//查找文件
  13. {
  14. listBox1.Items.Add(Dir+f.ToString());//listBox1中填加文件名
  15. }
  16. }
  17. catch(Exceptione)
  18. {
  19. MessageBox.Show(e.Message);
  20. }
  21. }

C#读取文件夹之方法调用情况:


  1. privatevoidbutton1_Click(objectsender,System.EventArgse)
  2. {
  3. stringcurrentdir="F://myprogram//C#//FileSearch";//搜索的目录
  4. if(currentdir[currentdir.Length-1]!='//')//非根目录
  5. currentdir+="//";
  6. FindFile(currentdir);//调用查找文件函数
  7. }

C#读取文件夹中的文件的基本的情况就向你介绍到这里,希望对你学习C#读取文件夹有所帮助。

转载声明:本文转自http://developer.51cto.com/art/200908/143613.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值