C#递归读取目录里所有文件(包括子目录)及其文件操作

本文介绍了一种递归搜索指定目录下所有特定类型文件的方法,并提供了一个简单的文本处理类实例,包括文件的打开、保存及打印功能。

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

用到两个函数ParseDirectory 和CreatePathList

void ParseDirectory(string path, string filter)
                
{    
                    
string[] dirs = Directory.GetDirectories(path);//得到子目录
                    IEnumerator iter = dirs.GetEnumerator();
                    
while(iter.MoveNext())
                    
{
                        
string str = (string)(iter.Current);
                        ParseDirectory(str, filter);
                    }

                    
string[] files = Directory.GetFiles(path, filter);
                    
if(files.Length > 0)
                    
{
                        m_numFiles 
+= files.Length;
                        m_pathList.Add(files);
                    }

}

 

string[] CreatePathList()
                
{
                    
if(m_numFiles <= 0)
                    
{
                        
return null;
                    }


                    
string[] str = new string[m_numFiles];
                    
int index = 0;

                    
try
                    
{
                        IEnumerator pathIter 
= m_pathList.GetEnumerator();
                        
while(pathIter.MoveNext())
                        
{
                            
string[] ar = (string[])(pathIter.Current);
                            IEnumerator fileIter 
= ar.GetEnumerator();
                            
while(fileIter.MoveNext())
                            
{
                                str[index] 
= (string)(fileIter.Current);
                                
++index;
                            }

                        }

                    }

                    
catch(Exception e)
                    
{
                        
return null;
                    }


                    
return str;
                }



使用范例:如果要查找的:d目录下所有mp3文件


string path="d://";    //目录名 也可以用相当路径
string filter="*.mp3";        //文件类型
 int m_numFiles=0;        //文件总数
 ArrayList m_pathList = new ArrayList();//包含所有文件路径的数组
string[] files;            //所有文件名
                
ParseDirectory(path, 
"*.mp3");
files
=CreatePathList();        //生成文件名数组
                if(files == null)
                
{
                    
throw new Exception(String.Concat("No file found in ", path));
                }


文件处理类

using  System  ;
        
using  System.Drawing  ;
        
using  System.Collections  ;
        
using  System.ComponentModel  ;
        
using  System.Windows.Forms  ;
        
using  System.Data  ;
        
using  System.IO  ;
        
using  System.Drawing.Printing  ;
    
public  class  Form1  :  Form
    
{
    
private  RichTextBox  richTextBox1  ;
    
private  Button  button1  ;
    
private  Button  button2  ;
    
private  Button  button3  ;
    
private  Button  button4  ;
    
private  Button  button5  ;
    
private  OpenFileDialog  openFileDialog1  ;
    
private  SaveFileDialog  saveFileDialog1  ;
    
private  PrintDialog  printDialog1  ;
    
private  PrintDocument  ThePrintDocument  ;
    
private  PrintPreviewDialog  printPreviewDialog1  ;
                        
private  StringReader  myReader  ;
    
private  System.ComponentModel.Container  components  =  null  ;
    
    
public  Form1  (  )
    
{
    
//初始化窗体中的各个组件
    InitializeComponent  (  )  ;
    }

    
//清除程序中使用多的资源
    protected  override  void  Dispose  (  bool  disposing  )
    
{
    
if  (  disposing  )
    
{
    
if  (  components  !=  null  )  
{
components.Dispose  (  )  ;
    }

    }

    
base.Dispose  (  disposing  )  ;
    }

    
private  void  InitializeComponent  (  )
    
{
    richTextBox1  
=  new  RichTextBox  (  )  ;
    button1  
=  new  Button  (  )  ;
    button2  
=  new  Button  (  )  ;
    button3  
=  new  Button  (  )  ;
    button4  
=  new  Button  (  )  ;
    button5  
=  new  Button  (  )  ;
                    saveFileDialog1  
=  new  SaveFileDialog  (  )  ;
                    openFileDialog1  
=  new  OpenFileDialog  (  )  ;
    printPreviewDialog1  
=  new  PrintPreviewDialog  (  )  ;
    printDialog1  
=  new  PrintDialog  (  )  ;
    ThePrintDocument  
=  new  PrintDocument  (  )  ;
                                                    ThePrintDocument.PrintPage  
+=  new  PrintPageEventHandler  (  ThePrintDocument_PrintPage  )  ;
    SuspendLayout  (  )  ;
    richTextBox1.Anchor  
=  AnchorStyles.None  ;
    richTextBox1.Name  
=  "richTextBox1"  ;
    richTextBox1.Size  
=  new  Size  (  448  ,  280  )  ;
    richTextBox1.TabIndex  
=  0  ;
    richTextBox1.Text  
=  ""  ;
    button1.Anchor  
=  AnchorStyles.None  ;
    button1.Location  
=  new  Point  (  41  ,  289  )  ;
    button1.Name  
=  "button1"  ;
    button1.Size  
=  new  Size  (  48  ,  30  )  ;
    button1.TabIndex  
=  1  ;
    button1.Text  
=  "打开"  ;
    button1.Click  
+=  new  System.EventHandler  (  button1_Click  )  ;
    button2.Anchor  
=  AnchorStyles.None  ;
    button2.Location  
=  new  Point  (  274  ,  288  )  ;
    button2.Name  
=  "button2"  ;
    button2.Size  
=  new  Size  (  48  ,  30  )  ;
    button2.TabIndex  
=  4  ;
    button2.Text  
=  "预览"  ;
    button2.Click  
+=  new  System.EventHandler  (  button2_Click  )  ;
    button3.Anchor  
=  AnchorStyles.None  ;
    button3.Location  
=  new  Point  (  108  ,  288  )  ;
    button3.Name  
=  "button3"  ;
    button3.Size  
=  new  Size  (  48  ,  30  )  ;
    button3.TabIndex  
=  2  ;
    button3.Text  
=  "保存"  ;
    button3.Click  
+=  new  System.EventHandler  (  button3_Click  )  ;
    button4.Anchor  
=  AnchorStyles.None  ;
    button4.Location  
=  new  Point  (  174  ,  288  )  ;
    button4.Name  
=  "button4"  ;
    button4.Size  
=  new  Size  (  80  ,  30  )  ;
    button4.TabIndex  
=  3  ;
    button4.Text  
=  "打印机设置"  ;
    button4.Click  
+=  new  System.EventHandler  (  button4_Click  )  ;
    button5.Anchor  
=  AnchorStyles.None  ;
    button5.Location  
=  new  Point  (  345  ,  288  )  ;
    button5.Name  
=  "button5"  ;
    button5.Size  
=  new  Size  (  48  ,  30  )  ;
    button5.TabIndex  
=  5  ;
    button5.Text  
=  "打印"  ;
    button5.Click  
+=  new  System.EventHandler  (  button5_Click  )  ;
                  saveFileDialog1.DefaultExt  
=  "*.txt"  ;
            saveFileDialog1.FileName  
=  "file.txt"  ;
    saveFileDialog1.InitialDirectory  
=  "c://"  ;
    saveFileDialog1.Title  
=  "另存为!"  ;
    openFileDialog1.DefaultExt  
=  "*.txt"  ;
    openFileDialog1.FileName  
=  "file.txt"  ;
    openFileDialog1.InitialDirectory  
=  "c://"  ;
    openFileDialog1.Title  
=  "打开文本文件!"  ;
    AutoScaleBaseSize  
=  new  Size  (  6  ,  14  )  ;
    ClientSize  
=  new  Size  (  448  ,  325  )  ;
    
this.Controls.Add  (  button1  )  ;
    
this.Controls.Add  (  button2  )  ;
    
this.Controls.Add  (  button3  )  ;
    
this.Controls.Add  (  button4  )  ;
    
this.Controls.Add  (  button5  )  ;
    
this.Controls.Add  (  richTextBox1  )  ;
    
    
this.MaximizeBox  =  false  ;
    
this.Name  =  "Form1"  ;
    
this.Text  =  "C#来操作文本文件"  ;
    
this.ResumeLayout  (  false  )  ;
    }

    
static  void  Main  (  )  
{
Application.Run  (  
new  Form1  (  )  )  ;
    }

    
    
private  void  button1_Click  (  object  sender  ,  System.EventArgs  e  )
    
{
                
try
                
{
    
if  (  openFileDialog1.ShowDialog  (  )  ==  DialogResult.OK  )
    
{
        FileStream  fs  
=  new  FileStream  (  openFileDialog1.FileName    ,  FileMode.Open  ,  FileAccess.Read  )  ;
        StreamReader  m_streamReader  
=  new  StreamReader  (  fs  )  ;  
    
//使用StreamReader类来读取文件
    m_streamReader.BaseStream.Seek  (  0  ,  SeekOrigin.Begin  )  ;
        
//  从数据流中读取每一行,直到文件的最后一行,并在richTextBox1中显示出内容
        this.richTextBox1.Text  =  ""  ;
        
string  strLine  =  m_streamReader.ReadLine  (  )  ;
        
while  (  strLine  !=  null  )
        
{
            
this.richTextBox1.Text  +=  strLine  +  "/n"  ;
            strLine  
=  m_streamReader.ReadLine  (  )  ;
        }

        
//关闭此StreamReader对象
        m_streamReader.Close  (  )  ;
    }
  
            }

            
catch  (  Exception  em  )
                
{
    Console.WriteLine  (  em.Message.ToString  (  )  )  ;
                }

    
    }

    
    
private  void  button3_Click  (  object  sender  ,  System.EventArgs  e  )
    
{
                
try
                
{
    
//获得另存为的文件名称
    if  (  saveFileDialog1.ShowDialog  (  )  ==  DialogResult.OK  )
    
{  
    
//创建一个文件流,用以写入或者创建一个StreamWriter
    FileStream  fs  =  new  FileStream  (  @saveFileDialog1.FileName    ,  FileMode.OpenOrCreate  ,  FileAccess.Write  )  ;
        StreamWriter  m_streamWriter  
=  new  StreamWriter  (  fs  )  ;
        m_streamWriter.Flush  (  )  ;
    
        
//  使用StreamWriter来往文件中写入内容
        m_streamWriter.BaseStream.Seek  (  0  ,  SeekOrigin.Begin  )  ;
        
//  把richTextBox1中的内容写入文件
        m_streamWriter.Write  (  richTextBox1.Text  )  ;
        
//关闭此文件
        m_streamWriter.Flush  (  )  ;
        m_streamWriter.Close  (  )  ;
    }

                }

                
catch  (  Exception  em  )
                
{
    Console.WriteLine  (  em.Message.ToString  (  )  )  ;
                }

    }

    
    
private  void  button4_Click  (  object  sender  ,  System.EventArgs  e  )
    
{
                printDialog1.Document  
=  ThePrintDocument  ;
                printDialog1.ShowDialog  (  )  ;
    }

    
//预览打印文档
    private  void  button2_Click  (  object  sender  ,  System.EventArgs  e  )
    
{
                
try
                
{
    
string  strText  =  richTextBox1.Text  ;
    myReader  
=  new  StringReader  (  strText  )  ;
    PrintPreviewDialog  printPreviewDialog1  
=  new  PrintPreviewDialog  (  )  ;
    printPreviewDialog1.Document  
=  ThePrintDocument    ;
    printPreviewDialog1.FormBorderStyle  
=  FormBorderStyle.Fixed3D    ;
    printPreviewDialog1.ShowDialog  (  )  ;
                }

                
catch  (  Exception  exp  )
                
{
    Console.WriteLine  (  exp.Message.ToString  (  )  )  ;
                }

    }

    
//打印richTextBox1中的内容
    private  void  button5_Click  (  object  sender  ,  System.EventArgs  e  )
    
{
                printDialog1.Document  
=  ThePrintDocument  ;
                
string  strText  =  richTextBox1.Text  ;
                myReader  
=  new  StringReader  (  strText  )  ;
                
if  (  printDialog1.ShowDialog  (  )  ==  DialogResult.OK  )
                
{
    ThePrintDocument.Print  (  )  ;
                }

    }

                
protected  void  ThePrintDocument_PrintPage  (  object  sender  ,  PrintPageEventArgs  ev  )
                            
{
                
float  linesPerPage  =  0  ;
                
float  yPosition  =  0  ;
                
int  count  =  0  ;
                
float  leftMargin  =  ev.MarginBounds.Left  ;
                
float  topMargin  =  ev.MarginBounds.Top  ;
                
string  line  =  null  ;
                Font  printFont  
=  richTextBox1.Font  ;
                SolidBrush  myBrush  
=  new  SolidBrush  (  Color.Black  )  ;
                
//计算每一页打印多少行  
            linesPerPage  =  ev.MarginBounds.Height  /  printFont.GetHeight  (  ev.Graphics  )  ;
                
//重复使用StringReader对象  ,打印出richTextBox1中的所有内容
                while  (  count  <  linesPerPage  &&  (  (  line  =  myReader.ReadLine  (  )  )  !=  null  )  )  
            
{
//  计算出要打印的下一行所基于页面的位置
    yPosition  =  topMargin  +  (  count  *  printFont.GetHeight  (  ev.Graphics  )  )  ;
    
//  打印出richTextBox1中的下一行内容
    ev.Graphics.DrawString  (  line  ,  printFont  ,  myBrush  ,  leftMargin  ,  yPosition  ,  new  StringFormat  (  )  )  ;
    count
++  ;
                }

                
//  判断如果还要下一页,则继续打印
                if  (  line  !=  null  )
    ev.HasMorePages  
=  true  ;
                
else
    ev.HasMorePages  
=  false  ;
                myBrush.Dispose  (  )  ;
      }

          }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值