国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#搜索文字在文件及文件夾中出現(xiàn)位置的方法

2020-01-24 01:32:05
字體:
供稿:網(wǎng)友

本文實例講述了C#搜索文字在文件及文件夾中出現(xiàn)位置的方法。分享給大家供大家參考。具體如下:

在linux中查詢文字在文件中出現(xiàn)的位置,或者在一個文件夾中出現(xiàn)的位置,用命令:

復(fù)制代碼 代碼如下:
grep -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ù)輸入進去就可以了

希望本文所述對大家的C#程序設(shè)計有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 沈丘县| 绵竹市| 桃源县| 台安县| 嘉峪关市| 蒙自县| 丽水市| 晋城| 阿城市| 松江区| 毕节市| 禄丰县| 安福县| 锡林浩特市| 东莞市| 泗洪县| 邯郸市| 兴化市| 天镇县| 商水县| 彭水| 天全县| 安溪县| 嘉善县| 沾益县| 额济纳旗| 新晃| 濮阳县| 保靖县| 勃利县| 滨州市| 安福县| 垦利县| 九龙城区| 荔浦县| 隆尧县| 合肥市| 息烽县| 自治县| 来凤县| 天长市|