۱۶-فروردین-۱۳۸۸, ۱۴:۴۰:۱۴
این کد در پوشه مورد نظر فایل های htm را باز کرده و در آن به دنبال کلمات مرتبط با Visual میگردد . ترکیبی از Regex,Linq
کد :
کد :
کد:
public static void Main()
{
// Modify this path as necessary.
string startFolder = @"c:\program files\Microsoft Visual Studio 9.0\";
// Take a snapshot of the file system.
IEnumerable<IO.FileInfo> fileList = GetFiles(startFolder);
// Create the regular expression to find all things "Visual".
Text.RegularExpressions.Regex searchTerm =
new Text.RegularExpressions.Regex(@"Visual (Basic|C#|C\+\+|J#|SourceSafe|Studio)");
// Search the contents of each .htm file.
var queryMatchingFiles =
from file in fileList
where file.Extension == ".htm"
let fileText = IO.File.ReadAllText(file.FullName)
let matches = searchTerm.Matches(fileText)
where searchTerm.Matches(fileText).Count > 0
select new
{
name = file.FullName,
matches = from Text.RegularExpressions.Match match in matches
select match.Value
};
// Execute the query.
Console.WriteLine("The term \"{0}\" was found in:", searchTerm.ToString());
foreach (var v in queryMatchingFiles)
{
// Trim the path a bit, then write
// the file name in which a match was found.
string s = v.name.Substring(startFolder.Length - 1);
Console.WriteLine(s);
// For this file, write out all the matching strings
foreach (var v2 in v.matches)
{
Console.WriteLine(" " + v2);
}
}
// Keep the console window open in debug mode
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
// This method assumes that the application has discovery
// permissions for all folders under the specified path.
static IEnumerable<IO.FileInfo> GetFiles(string path)
{
if (!IO.Directory.Exists(path))
throw new IO.DirectoryNotFoundException();
string[] fileNames = null;
List<IO.FileInfo> files = new List<IO.FileInfo>();
fileNames = IO.Directory.GetFiles(path, "*.*", IO.SearchOption.AllDirectories);
foreach (string name in fileNames)
{
files.Add(new IO.FileInfo(name));
}
return files;
}