C#搜索文字在文件及文件夹中出现位置的方法

前端技术 2023/09/05 C#

本文实例讲述了C#搜索文字在文件及文件夹中出现位置的方法。分享给大家供大家参考。具体如下:

在linux中查询文字在文件中出现的位置,或者在一个文件夹中出现的位置,用命令:

复制代码 代码如下:
grep -n \'需要查询的文字\' *

就可以了。今天做了一个C#程序,专门用来找出一个指定字符串在文件中的位置,与一个指定字符串在一个文件夹中所有的出现位置。

一、程序代码

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>
 /// 从文件中找关键字
 /// </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>
 /// 从文件夹中找关键字
 /// </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 地址 要查找的字符串

三、关于VS测试带有输入参数的程序

在项目属性→调试选项卡→启动选项→命令行参数,把参数输入进去就可以了

希望本文所述对大家的C#程序设计有所帮助。

本文地址:https://www.stayed.cn/item/14242

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。