C#搜索文字在文件及文件夾中出現(xiàn)位置的方法
本文實例講述了C#搜索文字在文件及文件夾中出現(xiàn)位置的方法。分享給大家供大家參考。具體如下:
在linux中查詢文字在文件中出現(xiàn)的位置,或者在一個文件夾中出現(xià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)文章
C#數(shù)據(jù)結(jié)構(gòu)之字符串(string)詳解
這篇文章主要介紹了C#數(shù)據(jù)結(jié)構(gòu)之字符串(string),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
C#實現(xiàn)的優(yōu)酷真實視頻地址解析功能(2014新算法)
這篇文章主要介紹了C#實現(xiàn)的優(yōu)酷真實視頻地址解析功能(2014新算法),本文在當(dāng)前環(huán)境下是有效的,因為優(yōu)酷之前更新了算法,需要的朋友可以參考下2014-10-10
淺談C#2.0泛型中的變化:default關(guān)鍵字
下面就詳細(xì)的說明一下。之所以會用到default關(guān)鍵字,是因為需要在不知道類型參數(shù)為值類型還是引用類型的情況下,為對象實例賦初值2013-09-09
C#中實現(xiàn)Fluent Interface的三種方法
這篇文章主要介紹了C#中實現(xiàn)Fluent Interface的三種方法,本文講解了Fluent Interface的簡單實現(xiàn)、使用裝飾器模式和擴展方法實現(xiàn)Fluent Interface等3種實現(xiàn)方法,需要的朋友可以參考下2015-03-03
在WPF中合并兩個ObservableCollection集合
這篇文章介紹了在WPF中合并兩個ObservableCollection集合的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

