I want to return an MVC view based on the filename passed into the controller function. However, the following requires a relative path:
[Route("/ReturnViewByFileName/{ViewName}")]
public ActionResult ReturnViewByFileName(string FileName)
{
return View("~/RelativePath");
}
Since I want to find a view file that is based on the parameter file name and I want to search a particular folder and sub folders for that file name.
var path = CurrentEnvironment.ContentRootPath + "\\Views\Parentfolder";
string[] FindFile = Directory.GetFiles(path, "*" + FileName +
"*", SearchOption.AllDirectories);
The problem is, this gives you the full file path of the file and not the relative file path that View() requires.
Is there a simple way to do one of the following:
- Override the View() function to accept a full file path
- Convert a full file path name to a relative file path
Or something else I am overlooking
Solution
public ActionResult FindMVCView(string FileName) { var path = CurrentEnvironment.ContentRootPath + "\\ParentFolder"; string[] FindFile = Directory.GetFiles(path, "*" + FileName + "*", SearchOption.AllDirectories); var newpath = FindFile[0].Replace(CurrentEnvironment.ContentRootPath, "~/").Replace(@"\", "/"); }