欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2015年08月18日 11:48:13   作者:北風(fēng)其涼  
這篇文章主要介紹了C#搜索文字在文件及文件夾中出現(xiàn)位置的方法,涉及C#針對文件及文件夾遍歷與查找的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了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ù)輸入進(jìn)去就可以了

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

相關(guān)文章

最新評論