栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
 }
 /// 
 /// 从文件中找关键字
 /// 
 /// 
 /// 
 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));
  }
  }
 }
 /// 
 /// 从文件夹中找关键字
 /// 
 /// 
 /// 
 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:TestProgramSearchSearchProgram.cs 中所有的 Console
在程序Search.exe所在目录下,输入命令:Search file/folder 地址 要查找的字符串

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124792.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号