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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

北风其凉   2021-03-21 我要评论
想了解C#搜索文字在文件及文件夹中出现位置的方法的相关内容吗,北风其凉在本文为您仔细讲解C#搜索文字在文件及文件夹中出现位置的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点: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#程序设计有所帮助。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们