生如夏花

生如夏花的.net 博客空间

导航

一个查找替换文件的简单工具

    之前做项目时,由于项目需要,需要实现一个简单的查找替换功能,

    如文件夹directoryA(包含子目录)中的有很多文件,文件filea是directorya中的一个文件,要实现的替换功能如下,如果filea中有一个字符串str1,则要找到该文件,将filea中的字符串str2替换成字符串str3,当时为了赶进度,以为有免费的查找替换工具,在网上找了半天,没找到类似的工具,而且好多老外的这种小东东,居然还要付money,后面自己干脆用c#写了个最简单的查找替换工具,其实也就是个简单的文件递归操作.大家如果有兴趣研究修改下,不断完善。争取也能做成个完善的小东东,收点money

效果图如下:

  代码如下,主要的调用方法是searchReplace,

private void btnSure_Click(object sender, System.EventArgs e)
        
{
            
try
            
{
                
string folderPath = txt_folder.Text;
                DirectoryInfo theFolder 
= new DirectoryInfo(folderPath);//目录名称
                string str1=txtString1.Text;//不包含字符串;
                string str2=txtString2.Text;//要替换的字符串;
                string str3=txtString3.Text;//替换成字符串;

                
if (theFolder.Exists)
                
{
                    searchReplace(theFolder.FullName,str1,str2,str3);
                    
                }

            MessageBox.Show(
"处理成功!");    
            }

            
catch(Exception ex)
            
{
                MessageBox.Show(ex.Message);
            }

        }


void searchReplace(string strFolder,string str1,string str2,string str3)
        
{
            DirectoryInfo theFolder 
= new DirectoryInfo(strFolder);//根目录名称
            FileInfo[] fis = theFolder.GetFiles();//找到该目录下所有文件
            foreach (FileInfo fi in fis) //循环
            {      //begin for
                bool blDo=true;
                StringBuilder sb 
= new StringBuilder();
                StreamReader sr 
=new StreamReader(fi.FullName,Encoding.GetEncoding("GB2312"));
            
                
string s = "";
                
while ((s = sr.ReadLine()) != null
                
{
                    
if(s.IndexOf(str1)!=-1)
                    
{
                        blDo
=false;        //找到有str1字符的文件了,        
                    }

                    
                    
int intPos=s.IndexOf(str2);    
                    
if(intPos!=-1)
                    
{
                        s
=s.Replace(str2,str3);    //替换                                    
                    }

                sb.Append(s
+"\r\n");//将替换后的所有写入到StringBuilder中.
                    
                    
                }
//end while            
                sr.Close();
                
if(blDo)
                
{
//                    MessageBox.Show(sb.ToString());
                    StreamWriter sw = new StreamWriter(fi.FullName,false,Encoding.GetEncoding("GB18030"));
                    sw.Write(sb);
//如果是要替换的文件,将StringBuilder回写到文件中。
                    sw.Close();
                }


            }
//end for
        
//递归调用
            foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())
            
{
                searchReplace(nextFolder.FullName,str1,str2,str3);
            }

 

源代码工程:https://files.cnblogs.com/l_dragon/Solution1.rar

 

posted on 2004-12-28 16:59  生如夏花之灿烂  阅读(2648)  评论(3编辑  收藏  举报