C#搜索文字在文件及文件夾中出現(xiàn)位置的方法
本文實例講述了C#搜索文字在文件及文件夾中出現(xiàn)位置的方法。分享給大家供大家參考。具體如下:
在linux中查詢文字在文件中出現(xiàn)的位置,或者在一個文件夾中出現(xiàn)的位置,用命令:
就可以了。今天做了一個C#程序,專門用來找出一個指定字符串在文件中的位置,與一個指定字符串在一個文件夾中所有的出現(xiàn)位置。
一、程序代碼
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Search { class Program { static void Main(string[] args) { if (args.Length != 3 || (args[0] != "file" && args[0] != "folder")) { Console.WriteLine("Correct Order Style: "); Console.WriteLine("Search file/folder address word"); } switch (args[0]) { case "file": //從文件中查找 { if (System.IO.File.Exists(args[1])) { FindInFile(args[1], args[2]); } else { Console.WriteLine(string.Format( "File {0} not exist!", args[1])); } } break; case "folder": //從文件夾中查找(包括其中全部文件) { if (System.IO.Directory.Exists(args[1])) { FindInDirectory(args[1], args[2]); } else { Console.WriteLine(string.Format( "Directory {0} not exist!", args[1])); } } break; default: break; } Console.WriteLine("Output Finished."); Console.ReadLine(); } /// <summary> /// 從文件中找關(guān)鍵字 /// </summary> /// <param name="filename"></param> /// <param name="word"></param> public static void FindInFile(string filename, string word) { System.IO.StreamReader sr = System.IO.File.OpenText(filename); string s = sr.ReadToEnd(); sr.Close(); string[] temp = s.Split('\n'); for (int i = 0; i < temp.Length; i++) { if (temp[i].IndexOf(word) != -1) { Console.WriteLine(string.Format( "Found in: {0}\n{1}\nLine: {2} \n", filename, temp[i].Trim(), i + 1)); } } } /// <summary> /// 從文件夾中找關(guān)鍵字 /// </summary> /// <param name="foldername"></param> /// <param name="word"></param> public static void FindInDirectory(string foldername, string word) { System.IO.DirectoryInfo dif = new System.IO.DirectoryInfo(foldername); //遍歷文件夾中的各子文件夾 foreach (System.IO.DirectoryInfo di in dif.GetDirectories()) { FindInDirectory(di.FullName, word); } //查詢文件夾中的各個文件 foreach (System.IO.FileInfo f in dif.GetFiles()) { FindInFile(f.FullName, word); } } } }
二、運行示例
查找文件 E:\TestProgram\Search\Search\Program.cs 中所有的 Console
在程序Search.exe所在目錄下,輸入命令:Search file/folder 地址 要查找的字符串
三、關(guān)于VS測試帶有輸入?yún)?shù)的程序
在項目屬性→調(diào)試選項卡→啟動選項→命令行參數(shù),把參數(shù)輸入進(jìn)去就可以了
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
Unity基于ShaderLab實現(xiàn)光照系統(tǒng)(著色器代碼實現(xiàn)小結(jié))
這篇文章主要介紹了Unity基于ShaderLab實現(xiàn)光照系統(tǒng),主要總結(jié)unity中shaderlab的著色器代碼實現(xiàn),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-01-01C#實現(xiàn)自定義光標(biāo)并動態(tài)切換
這篇文章主要為大家詳細(xì)介紹了如何利用C#語言實現(xiàn)自定義光標(biāo)、并動態(tài)切換光標(biāo)類型,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-07-07c#實現(xiàn)萬年歷示例分享 萬年歷農(nóng)歷查詢
這篇文章主要介紹了c#實現(xiàn)萬年歷的方法,可以顯示農(nóng)歷、節(jié)氣、節(jié)日、星座、星宿、屬相、生肖、閏年月、時辰,大家參考使用吧2014-01-01