如何在mvc

时间:2016-07-13 08:57:11

标签: c# asp.net-mvc

我的MVC项目的视图文件夹中有很多 .cshtml 页面。在我的布局页面中有可用的搜索选项,所以当有人搜索任何单词时,我想在所有 .cshtml 页面中搜索该单词并返回视图名称。 我怎样才能在MVC中实现这一目标?

1 个答案:

答案 0 :(得分:1)

可能的方法:

string path = Server.MapPath("~/Views"); //path to start searching.
if (Directory.Exists(path))
{
    ProcessDirectory(path);
}
//Loop through each file and directory of provided path.
public void ProcessDirectory(string targetDirectory)
{
     // Process the list of files found in the directory.
     string[] fileEntries = Directory.GetFiles(targetDirectory);
     foreach (string fileName in fileEntries)
     {
          string found = ProcessFile(fileName);
     }
     //Recursive loop through subdirectories of this directory.
     string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
     foreach (string subdirectory in subdirectoryEntries)
     {
          ProcessDirectory(subdirectory);
     }
}
//Get contents of file and search specified text.
public string ProcessFile(string filepath)
{
    string content = string.Empty;
    string strWordSearched = "test";

    using (var stream = new StreamReader(filepath))
    {
         content = stream.ReadToEnd();
         int index = content.IndexOf(strWordSearched);
         if (index > -1)
         {
              return Path.GetFileName(filepath);
         }
     } 
 }