C#-文件操作大全文庫_第1頁
C#-文件操作大全文庫_第2頁
C#-文件操作大全文庫_第3頁
C#-文件操作大全文庫_第4頁
C#-文件操作大全文庫_第5頁
已閱讀5頁,還剩86頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

//usingSystem.IO;Directory.CreateDirectory(%%1);//usingSystem.IO;File.Create(%%1);//usingSystem.IO;File.Delete(%%1);//usingSystem.IO;Directory.Delete(%%1);//usingSystem.IO;foreach(stringdirStrinDirectory.GetDirectories(%%1)){ DirectoryInfodir=newDirectoryInfo(dirStr); ArrayListfolders=newArrayList(); FileSystemInfo[]fileArr=dir.GetFileSystemInfos(); for(inti=0;i<folders.Count;i++) { FileInfof=folders[i]asFileInfo; if(f==null) { DirectoryInfod=folders[i]asDirectoryInfo; d.Delete(); } }}6.清空文件夾//usingSystem.IO;Directory.Delete(%%1,true);Directory.CreateDirectory(%%1);//usingSystem.IO;StreamReaders=File.OpenText(%%1);string%%2=null;while((%%2=s.ReadLine())!=null){ %%3}s.Close();//usingSystem.IO;FileInfof=newFileInfo(%%1);StreamWriterw=f.CreateText();w.WriteLine(%%2);w.Close();//usingSystem.IO;byte[]dataArray=newbyte[100000];//newRandom().NextBytes(dataArray);ate)){//Writethedatatothefile,bytebybyte. for(inti=0;i<dataArray.Length;i++){ FileStream.WriteByte(dataArray[i]); }//Setthestreampositiontothebeginningofthefile. FileStream.Seek(0,SeekOrigin.Begin);//Readandverifythedata. for(inti=0;i<FileStream.Length;i++){ if(dataArray[i]!=FileStream.ReadByte()){ //寫入數(shù)據(jù)錯誤 return; } }//"數(shù)據(jù)流"+FileStream.Name+"已驗證"}//usingSystem.IO;if((f.Attributes&FileAttributes.ReadOnly)!=0){ %%2}else{ %%3}//usingSystem.IO;FileInfof=newFileInfo(%%1);//設(shè)置只讀f.Attributes=myFile.Attributes|FileAttributes.ReadOnly;//設(shè)置可寫f.Attributes=myFile.Attributes&~FileAttributes.ReadOnly;//usingSystem.IO;foreach(string%%2inDirectory.GetDirectories(%%1)){ %%3}/*DirectoryInfodir=newDirectoryInfo(%%1);FileInfo[]files=dir.GetFiles("*.*");foreach(FileInfo%%2infiles){ %%3}*//*usingSystem.IO;usingSystem.Collections;*/stringpath=(%%2.LastIndexOf("\\")==%%2.Length-1)?%%2:%%2+"\\";stringparent=Path.GetDirectoryName(%%1);Directory.CreateDirectory(path+Path.GetFileName(%%1));DirectoryInfodir=newDirectoryInfo((%%1.LastIndexOf("\\")==%%1.Length-1)?%%1:%%1+"\\");FileSystemInfo[]fileArr=dir.GetFileSystemInfos();Queue<FileSystemInfo>Folders=newQueue<FileSystemInfo>(dir.GetFileSystemInfos());while(Folders.Count>0){FileSystemInfotmp=Folders.Dequeue();FileInfof=tmpasFileInfo;if(f==null){DirectoryInfod=tmpasDirectoryInfo;Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\\")==parent.Length-1)?parent:parent+"\\",path));foreach(FileSystemInfofiind.GetFileSystemInfos()){Folders.Enqueue(fi);}}else{f.CopyTo(f.FullName.Replace(parent,path));}}/*usingSystem.IO;usingSystem.Collections;*/DirectoryInfod=newDirectoryInfo(%%1);foreach(DirectoryInfodirsind.GetDirectories()){Queue<FileSystemInfo>al=newQueue<FileSystemInfo>(dirs.GetFileSystemInfos());while(al.Count>0){FileSystemInfotemp=al.Dequeue();FileInfofile=tempasFileInfo;if(file==null){DirectoryInfodirectory=tempasDirectoryInfo;Directory.CreateDirectory(path+directory.Name);foreach(FileSystemInfofsiindirectory.GetFileSystemInfos())al.Enqueue(fsi);}else,path+file.Name);}}/*usingSystem.IO;usingSystem.Collections;*/stringfilename=Path.GetFileName(%%1);stringpath=(%%2.LastIndexOf("\\")==%%2.Length-1)?%%2:%%2+"\\";if(Path.GetPathRoot(%%1)==Path.GetPathRoot(%%2))Directory.Move(%%1,path+filename);else{stringparent=Path.GetDirectoryName(%%1);Directory.CreateDirectory(path+Path.GetFileName(%%1));DirectoryInfodir=newDirectoryInfo((%%1.LastIndexOf("\\")==%%1.Length-1)?%%1:%%1+"\\");FileSystemInfo[]fileArr=dir.GetFileSystemInfos();Queue<FileSystemInfo>Folders=newQueue<FileSystemInfo>(dir.GetFileSystemInfos());while(Folders.Count>0){FileSystemInfotmp=Folders.Dequeue();FileInfof=tmpasFileInfo;if(f==null){DirectoryInfod=tmpasDirectoryInfo;DirectoryInfodpath=newDirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\\")==parent.Length-1)?parent:parent+"\\",path));dpath.Create();foreach(FileSystemInfofiind.GetFileSystemInfos()){Folders.Enqueue(fi);}}else{f.MoveTo(f.FullName.Replace(parent,path));}}Directory.Delete(%%1,true);}/*usingSystem.IO;usingSystem.Collections;*/stringfilename=Path.GetFileName(%%1);if(Path.GetPathRoot(%%1)==Path.GetPathRoot(%%2))foreach(stringdirinDirectory.GetDirectories(%%1))Directory.Move(dir,Path.Combine(%%2,filename));else{foreach(stringdir2inDirectory.GetDirectories(%%1)){stringparent=Path.GetDirectoryName(dir2);Directory.CreateDirectory(Path.Combine(%%2,Path.GetFileName(dir2)));stringdir=(dir2.LastIndexOf("\\")==dir2.Length-1)?dir2:dir2+"\\";DirectoryInfodirdir=newDirectoryInfo(dir);FileSystemInfo[]fileArr=dirdir.GetFileSystemInfos();Queue<FileSystemInfo>Folders=newQueue<FileSystemInfo>(dirdir.GetFileSystemInfos());while(Folders.Count>0){FileSystemInfotmp=Folders.Dequeue();FileInfof=tmpasFileInfo;if(f==null){DirectoryInfod=tmpasDirectoryInfo;DirectoryInfodpath=newDirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\\")==parent.Length-1)?parent:parent+"\\",%%2));dpath.Create();foreach(FileSystemInfofiind.GetFileSystemInfos()){Folders.Enqueue(fi);}}else{f.MoveTo(f.FullName.Replace(parent,%%2));}}dirdir.Delete(true);}}/*usingSystem.IO;usingSystem.Collections;*/boolb=false;stringpath=(%%2.LastIndexOf("\\")==%%2.Length-1)?%%2:%%2+"\\";stringparent=Path.GetDirectoryName(%%1);Name(%%1));DirectoryInfodir=newDirectoryInfo((%%1.LastIndexOf("\\")==%%1.Length-1)?%%1:%%1+"\\");FileSystemInfo[]fileArr=dir.GetFileSystemInfos();Queue<FileSystemInfo>Folders=newQueue<FileSystemInfo>(dir.GetFileSystemInfos());while(Folders.Count>0){FileSystemInfotmp=Folders.Dequeue();FileInfof=tmpasFileInfo;if(f==null){DirectoryInfod=tmpasDirectoryInfo;Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\\")==parent.Length-1)?parent:parent+"\\",path));foreach(FileSystemInfofiind.GetFileSystemInfos()){Folders.Enqueue(fi);}}else{if(b)File.Create(f.FullName.Replace(parent,path));}}//usingSystem.IO;File.Copy(%%1,%%2);//usingSystem.IO;foreach(stringfileStrinDirectory.GetFiles(%%1))e(fileStr),(%%2.LastIndexOf("\\")==%%2.Length-1)?%%2+Path.GetFileName(fileStr):%%2+"\\"+Path.GetFileName(fileStr));//usingSystem.IO;string%%2=Path.GetExtension(%%1);//usingSystem.IO;string%%2=Path.GetFileName(%%1);//usingSystem.IO;string%%2=Path.GetDirectoryName(%%1);//usingSystem.IO;File.ChangeExtension(%%1,%%2);//usingSystem.IO;string%%3=Path.Combine(%%1,%%2);//usingSystem.IO;e(%%1));foreach(stringfileStrinDirectory.GetFiles(%%1)) File.Move((%%1.LastIndexOf("\\")==%%1.Length-1)?%%1+Path.GetFileName(fileStr):%%1+"\\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\")==%%2.Length-1)?%%2+Path.GetFileName(fileStr):%%2+"\\"+Path.GetFileName(fileStr));/*usingSystem.Text;usingSystem.IO;*/stringfileName=%%1;stringdirName=%%2; DirectoryInfodirc=newDirectoryInfo(dirName);etFiles()){ if(file.Name.IndexOf(fileName)>-1) returnfile.FullName; } foreach(DirectoryInfodirindirc.GetDirectories()){ returnGetFile(fileName,dir.FullName); } return"找不到指定的文件"; }OpenFileDialogopenFileDialog=newOpenFileDialog();openFileDialog.InitialDirectory=\"c:\\\\\";//注意這里寫路徑時要用c:\\\\而不是c:\\openFileDialog.Filter=\"文本文件|*.*|C#文件|*.cs|所有文件|*.*\";openFileDialog.RestoreDirectory=true;openFileDialog.FilterIndex=1;og()==DialogResult.OK){ fName=openFileDialog.FileName; FilefileOpen=newFile(fName); isFileHaveName=true; %%1=fileOpen.ReadFile(); %%1.AppendText(\"\");}//usingSystem.IO;FileStreamfsr=newFileStream(%%1,FileMode.Open,FileAccess.Read);byte[]btArr=newbyte[fsr.Length];fsr.Read(btArr,0,btArr.Length);fsr.Close();stringstrFileName=%%1.Substring(%%1.LastIndexOf("\\")+1);FileStreamfsw=newFileStream(%%2+strFileName+"1",FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length/2);fsw.Close();fsw=newFileStream(%%2+strFileName+"2",FileMode.Create,FileAccess.Write);fsw.Write(btArr,btArr.Length/2,btArr.Length-btArr.Length/2);fsw.Close();//usingSystem.IO;stringstrFileName=%%1.Substring(%%1.LastIndexOf("\\")+1);FileStreamfsr1=newFileStream(%%2+strFileName+"1",FileMode.Open,FileAccess.Read);FileStreamfsr2=newFileStream(%%2+strFileName+"2",FileMode.Open,FileAccess.Read);byte[]btArr=newbyte[fsr1.Length+fsr2.Length];fsr1.Read(btArr,0,Convert.ToInt32(fsr1.Length));fsr2.Read(btArr,Convert.ToInt32(fsr1.Length),Convert.ToInt32(fsr2.Length));fsr1.Close();fsr2.Close();FileStreamfsw=newFileStream(%%2+strFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();//usingSystem.IO;//讀文件FileStreamfsr=newFileStream(%%1,FileMode.Open,FileAccess.Read);byte[]btArr=newbyte[fsr.Length];fsr.Read(btArr,0,btArr.Length);fsr.Close();for(inti=0;i<btArr.Length;i++){//加密 intibt=btArr[i]; ibt+=100; ibt%=256; btArr[i]=Convert.ToByte(ibt);}//寫文件stringstrFileName=Path.GetExtension(%%1);FileStreamfsw=newFileStream(%%2+"/"+"enc_"+strFileName,FileMode.Create,FileAccess.Write); fsw.Write(btArr,0,btArr.Length);se();//usingSystem.IO;FileStreamfsr=newFileStream(%%1,FileMode.Open,FileAccess.Read);byte[]btArr=newbyte[fsr.Length];fsr.Read(btArr,0,btArr.Length);fsr.Close();for(inti=0;i<btArr.Length;i++){//解密 intibt=btArr[i]; ibt-=100; ibt+=256; ibt%=256; btArr[i]=Convert.ToByte(ibt);}//寫文件stringstrFileName=Path.GetExtension(%%1);FileStreamfsw=newFileStream(%%2+"/"+strFileName,FileMode.Create,FileAccess.Write);fsw.Write(btArr,0,btArr.Length);fsw.Close();//usingSystem.Runtime.InteropServices;//[DllImport("kernel32")]//返回取得字符串緩沖區(qū)的長度//privatestaticexternlongGetPrivateProfileString(stringsection,stringkey,stringdef,StringBuilderretVal,intsize,stringfilePath);stringSection=%%1;stringKey=%%2;stringNoText=%%3;stringiniFilePath="Setup.ini";string%%4=String.Empty; if(File.Exists(iniFilePath)){ StringBuildertemp=newStringBuilder(1024); GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath); %%4=temp.ToString(); }//usingSystem.IO;FileStreamfsw=newFileStream(%%2,FileMode.Create,FileAccess.Write);foreach(stringfileStrinDirectory.GetFiles(%%1)){FileStreamfsr1=newFileStream(fileStr,FileMode.Open,FileAccess.Read);byte[]btArr=newbyte[fsr1.Length];fsr1.Read(btArr,0,Convert.ToInt32(fsr1.Length));fsr1.Close();fsw.Write(btArr,0,btArr.Length);}fsw.Close();//usingSystem.Runtime.InteropServices;//[DllImport("kernel32")]//返回0表示失敗,非0為成功//privatestaticexternlongWritePrivateProfileString(stringsection,stringkey,stringval,stringfilePath);stringSection=%%1;stringKey=%%2;stringValue=%%3;stringiniFilePath="Setup.ini";bool%%4=false;if(File.Exists(iniFilePath)){longOpStation=WritePrivateProfileString(Section,Key,Value,iniFilePath);if(OpStation==0){%%4=false;}else{%%4=true;}}string%%1=Environment.CurrentDirectory;//usingSystem.Xml;XmlDocumentdoc=newXmlDocument();doc.Load(%%1);string%%9;XmlElementxe=doc.GetElementById(%%7);XmlNodeListelemList=xe.ChildNodes;foreach(XmlNodeeleminelemList){if(elem.NodeType==%%8){%%9=elem.Value;break;}}//usingSystem.Xml;XmlDocumentdoc=newXmlDocument();doc.Load(%%1);XmlNoderoot=doc.DocumentElement;XmlElementbook=doc.CreateElement(%%3);XmlElementbook=doc.CreateElement(%%5);XmlElementport=doc.CreateElement(%%6);book.SetAttribute(%%4,root.ChildNodes.Count.ToString());author.InnerText=%%8;book.appendChild(author);book.appendChild(port);root.appendChild(book);doc.Save(%%1);/*usingSystem.IO;pression;*/FileStreaminfile;try{ //OpenthefileasaFileStreamobject. infile=newFileStream(%%1,FileMode.Open,FileAccess.Read,FileShare.Read); byte[]buffer=newbyte[infile.Length]; //Readthefiletoensureitisreadable. intcount=infile.Read(buffer,0,buffer.Length); if(count!=buffer.Length) { infile.Close();//TestFailed:Unabletoreaddatafromfile return; } infile.Close(); MemoryStreamms=newMemoryStream(); //Usethenewlycreatedmemorystreamforthecompresseddata. DeflateStreamcompressedzipStream=newDeflateStream(ms,CompressionMode.Compress,true); //Compression compressedzipStream.Write(buffer,0,buffer.Length); //Closethestream. compressedzipStream.Close(); //Originalsize:{0},Compressedsize:{1}",buffer.Length,ms.Length); FileInfof=newFileInfo(%%2); StreamWriterw=f.CreateText(); w.Write(buffer,0,ms.Length); w.Close();}//endtrycatch(InvalidDataException){ //Error:Thefilebeingreadcontainsinvaliddata.}catch(FileNotFoundException){ //Error:Thefilespecifiedwasnotfound.}catch(ArgumentException){ //Error:pathisazero-lengthstring,containsonlywhitespace,orcontainsoneormoreinvalidcharacters}catch(PathTooLongException){ //Error:Thespecifiedpath,filename,orbothexceedthesystem-definedmaximumlength.Forexample,onWindows-based platforms,pathsmustbelessthan248characters,andfilenamesmustbelessthan260characters.}catch(DirectoryNotFoundException){ //Error:Thespecifiedpathisinvalid,suchasbeingonanunmappeddrive.}catch(IOException){ //Error:AnI/Oerroroccurredwhileopeningthefile.}catch(UnauthorizedAccessException){ //Error:pathspecifiedafilethatisread-only,thepathisadirectory,orcallerdoesnothavetherequired permissions.}catch(IndexOutOfRangeException){ //Error:YoumustprovideparametersforMyGZIP.}/*usingSystem.IO;usingSystem.IO.Compression;*/FileStreaminfile;try{//OpenthefileasaFileStreamobject.infile=newFileStream(%%1,FileMode.Open,FileAccess.Read,FileShare.Read);];//Readthefiletoensureitisreadable.intcount=infile.Read(buffer,0,buffer.Length);if(count!=buffer.Length){infile.Close();//TestFailed:Unabletoreaddatafromfilereturn;}infile.Close();MemoryStreamms=newMemoryStream();//ms.Position=0;DeflateStreamzipStream=newDeflateStream(ms,CompressionMode.Decompress);//Decompressionbyte[]decompressedBuffer=newbyte[buffer.Length*2];zipStream.Close();FileInfof=newFileInfo(%%2);StreamWriterw=f.CreateText();w.Write(decompressedBuffer);w.Close();}//endtrycatch(InvalidDataException){//Error:Thefilebeingreadcontainsinvaliddata.}catch(FileNotFoundException){//Error:Thefilespecifiedwasnotfound.}catch(ArgumentException){//Error:pathisazero-lengthstring,containsonlywhitespace,orcontainsoneormoreinvalidcharacters}catch(PathTooLongException){//Error:Thespecifiedpath,filename,orbothexceedthesystem-definedmaximumlength.Forexample,onWindows-basedplatforms,pathsmustbelessthan248characters,andfilenamesmustbelessthan260characters.}catch(DirectoryNotFoundException){//Error:Thespecifiedpathisinvalid,suchasbeingonanunmappeddrive.}catch(IOException){//Error:AnI/Oerroroccurredwhileopeningthefile.}catch(UnauthorizedAccessException){//Error:pathspecifiedafilethatisread-only,thepathisadirectory,orcallerdoesnothavetherequiredpermissions.}catch(IndexOutOfRangeException){//Error:YoumustprovideparametersforMyGZIP.}string%%1=Application.ExecutablePath;/*usingSystem.IO;usingSystem.IO.Compression;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Formatters.Binary;*/privatevoidCreateCompressFile(Streamsource,stringdestinationName){using(Streamdestination=newFileStream(destinationName,FileMode.Create,FileAccess.Write)){using(GZipStreamoutput=newGZipStream(destination,CompressionMode.Compress)){byte[]bytes=newbyte[4096];intn;while((n=source.Read(bytes,0,bytes.Length))!=0){output.Write(bytes,0,n);}}}}ArrayListlist=newArrayList();foreach(stringfinDirectory.GetFiles(%%1)){byte[]destBuffer=File.ReadAllBytes(f);SerializeFileInfosfi=newSerializeFileInfo(f,destBuffer);list.Add(sfi);}IFormatterformatter=newBinaryFormatter();using(Streams=newMemoryStream()){formatter.Serialize(s,list);s.Position=0;CreateCompressFile(s,%%2);}[Serializable]classSerializeFileInfo{publicSerializeFileInfo(stringname,byte[]buffer){fileName=name;fileBuffer=buffer;}stringfileName;publicstringFileName{get{returnfileName;}}byte[]fileBuffer;publicbyte[]FileBuffer{get{returnfileBuffer;}}}//usingSystem.IO;DirectoryInfoDInfo=newDirectoryInfo(%%1);eSystemInfos();for(inti=0;i<FSInfo.Length;i++){FileInfoFInfo=newFileInfo(%%1+FSInfo[i].ToString());FInfo.Delete();}/*usingSystem.Xml;usingSystem.Xml.Schema;*/XmlReaderSettingssettings=newXmlReaderSettings();td=false;settings.ValidationType=ValidationType.DTD;settings.ValidationEventHandler+=newValidationEventHandler(ValidationCallBack);//CreatetheXmlReaderobject.XmlReaderreader=XmlReader.Create("mybook.xml",settings);//Parsethefile.while(reader.Read());//Displayanyvalidationerrors.privatestaticvoidValidationCallBack(objectsender,ValidationEventArgse){Console.WriteLine("ValidationError:{0}",e.Message);}45.Schema驗證/*usingSystem.Xml;usingSystem.Xml.Schema;*/Booleanm_success;XmlValidatingReaderreader=null;XmlSchemaCollectionmyschema=newXmlSchemaCollection();ValidationEventHandlereventHandler=newValidationEventHandler(ShowCompileErrors);try{//CreatetheXMLfragmenttobeparsed.StringxmlFrag="<authorxmlns='urn:bookstore-schema'xmlns:xsi=':///2001/XMLSchema-instance'>"+"<first-name>Herman</first-name>"+"<last-name>Melville</last-name>"+"</author>";//CreatetheXmlParserContext.XmlParserContextcontext=newXmlParserContext(null,null,"",XmlSpace.None);//Implementthereader.reader=newXmlValidatingReader(xmlFrag,XmlNodeType.Element,context);//Addtheschema.myschema.Add("urn:bookstore-schema","c:\\Books.xsd");//Settheschematypeandaddtheschematothereader.reader.ValidationType=ValidationType.Schema;reader.Schemas.Add(myschema);while(reader.Read()){}Console.WriteLine("Completedvalidatingxmlfragment");}catch(XmlExceptionXmlExp){Console.WriteLine(XmlExp.Message);}catch(XmlSchemaExceptionXmlSchExp){Console.WriteLine(XmlSchExp.Message);}catch(ExceptionGenExp){Console.WriteLine(GenExp.Message);}finally{Console.Read();}publicstaticvoidShowCompileErrors(objectsender,ValidationEventArgsargs){Console.WriteLine("ValidationError:{0}",args.Message);}/*usingSystem.Collections;usingSystem.Text.RegularExpressions;usingSystem.IO;usingSystem.Security;usingCommandLine.Utility;*///Traditionallygrepstandsfor"GlobalRegularExpressionPrint".//Globalmeansthatanentirefileissearched.//RegularExpressionmeansthataregularexpressionstringisusedtoestablishasearchpattern.//Printmeansthatthecommandwilldisplayitsfindings.//Simplyput,grepsearchesanentirefileforthepatternyouwantanddisplaysitsfindings.////TheusesyntaxisdifferentfromthetraditionalUnixsyntax,Ipreferasyntaxsimilarto//csc,theC#compiler.////grep[/h|/H]-UsageHelp////grep[/c][/i][/l][/n][/r]/E:reg_exp/F:files/////c-printacountofmatchinglinesforeachinputfile;///i-ignorecaseinpattern;///l-printjustfiles(scanningwillstoponfirstmatch);///n-prefixeachlineofoutputwithlinenumber;///r-recursivesearchinsubdirectories;/////E:reg_exp-theRegularExpressionusedassearchpattern.TheRegularExpressioncanbedelimitedby//quoteslike"..."and'...'ifyouwanttoincludeinitleadingortrailingblanks;/////F:files-thelistofinputfiles.Thefilescanbeseparatedbycommasasin/F:file1,file2,file3//andwildcardscanbeusedfortheirspecificationasin/F:*file?.txt;////Example:////grep/c/n/r/E:"CSharp"/F:*.cs//OptionFlagsprivateboolm_bRecursive;privateboolm_bIgnoreCase;privateboolm_bJustFiles;privateboolm_bLineNumbers;privateboolm_bCountLines;privatestringm_strRegEx;privatestringm_strFiles;//ArrayListkeepingtheFilesprivateArrayListm_arrFiles=newArrayList();//PropertiespublicboolRecursive{get{returnm_bRecursive;}set{m_bRecursive=value;}}publicboolIgnoreCase{get{returnm_bIgnoreCase;}set{m_bIgnoreCase=value;}}publicboolJustFiles{get{returnm_bJustFiles;}set{m_bJustFiles=value;}}publicboolLineNumbers{get{returnm_bLineNumbers;}set{m_bLineNumbers=value;}}publicboolCountLines{get{returnm_bCountLines;}set{m_bCountLines=value;}}publicstringRegEx{get{returnm_strRegEx;}set{m_strRegEx=value;}}publicstringFiles{get{returnm_strFiles;}set{m_strFiles=value;}}//BuildthelistofFilesprivatevoidGetFiles(StringstrDir,StringstrExt,boolbRecursive){//searchpatterncanincludethewildcharacters'*'and'?'string[]fileList=Directory.GetFiles(strDir,strExt);for(inti=0;i<fileList.Length;i++){if(File.Exists(fileList[i]))m_arrFiles.Add(fileList[i]);}if(bRecursive==true){//Getrecursivelyfromsubdirectoriesstring[]dirList=Directory.GetDirectories(strDir);for(inti=0;i<dirList.Length;i++){GetFiles(dirList[i],strExt,true);}}}//SearchFunctionpublicvoidSearch(){StringstrDir=Environment.CurrentDirectory;//Firstemptythelistm_arrFiles.Clear();//CreaterecursivelyalistwithallthefilescomplyingwiththecriteriaString[]astrFiles=m_strFiles.Split(newChar[]{','});for(inti=0;i<astrFiles.Length;i++){//EliminatewhitespacesastrFiles[i]=astrFiles[i].Trim();GetFiles(strDir,astrFiles[i],m_bRecursive);}//NowalltheFilesareintheArrayList,openeachone//iterativelyandlookforthesearchstringStringstrResults="GrepResults:\r\n\r\n";StringstrLine;intiLine,iCount;boolbEmpty=true;IEnumeratorenm=m_arrFiles.GetEnumerator();while(enm.MoveNext()){try{StreamReadersr=File.OpenText((string)enm.Current);iLine=0;iCount=0;boolbFirst=true;while((strLine=sr.ReadLine())!=null){iLine++;//UsingRegularExpressionsasarealGrepMatchmtch;if(m_bIgnoreCase==true)mtch=Regex.Match(strLine,m_strRegEx,RegexOptions.IgnoreCase);elsemtch=Regex.Match(strLine,m_strRegEx);if(mtch.Success==true){bEmpty=false;iCount++;if(bFirst==true){if(m_bJustFiles==true){strResults+=(string)enm.Current+"\r\n";break;}elsestrResults+=(string)enm.Current+":\r\n";bFirst=false;}//AddtheLinetoResultsstringif(m_bLineNumbers==true)strResults+=""+iLine+":"+strLine+"\r\n";elsestrResults+=""+strLine+"\r\n";}}sr.Close();if(bFirst==false){if(m_bCountLines==true)strResults+=""+iCount+"LinesMatched\r\n";strResults+="\r\n";}}catch(SecurityException){strResults+="\r\n"+(string)enm.Current+":SecurityException\r\n\r\n";}catch(FileNotFoundException){strResults+="\r\n"+(string)enm.Current+":FileNotFoundException\r\n";}}if(bEmpty==true)Console.WriteLine("Nomatchesfound!");elseConsole.WriteLine(strResults);}//PrintHelpprivatestaticvoidPrintHelp(){Console.WriteLine("Usage:grep[/h|/H]");Console.WriteLine("grep[/c][/i][/l][/n][/r]/E:reg_exp/F:files");}ArgumentsCommandLine=newArguments(args);if(CommandLine["h"]!=null||CommandLine["H"]!=null){PrintHelp();return;}//TheworkingobjectConsoleGrepgrep=newConsoleGrep();//Thearguments/eand/faremandatoryif(CommandLine["E"]!=null)grep.RegEx=(string)CommandLine["E"];else{Console.WriteLine("Error:NoRegularExpressionspecified!");Console.WriteLine();PrintHelp();return;}if(CommandLine["F"]!=null)grep.Files=(string)CommandLine["F"];else{Console.WriteLine("Error:NoSearchFilesspecified!");Console.WriteLine();PrintHelp();return;}grep.Recursive=(CommandLine["r"]!=null);grep.IgnoreCase=(CommandLine["i"]!=null);grep.JustFiles=(CommandLine["l"]!=null);if(grep.JustFiles==true)grep.LineNumbers=false;elsegrep.LineNumbers=(CommandLine["n"]!=null);if(grep.JustFiles==true)grep.CountLines=false;elsegrep.CountLines=(CommandLine["c"]!=null);//Dothesearchgrep

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論