0

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:

  1. Override the View() function to accept a full file path
  2. Convert a full file path name to a relative file path
  3. 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(@"\", "/");
    }
    
Watson
  • 1,385
  • 1
  • 15
  • 36
  • The view file is inside your project or not? I think the answer is yes, refer to this: https://stackoverflow.com/questions/1421854/accessing-views-with-absolute-paths-on-asp-net-mvc You don't have to pass the full path in, just use it starting from ~/Views/xxxx. – wannadream Oct 31 '18 at 23:08
  • Yes but I have to shape the path string from System.IO into the relative path string for View(). Which is option 2. I was hoping there was an in-build function to do this. – Watson Oct 31 '18 at 23:19
  • 1
    Okay, take a look at this post: https://stackoverflow.com/questions/3164/absolute-path-back-to-web-relative-path – wannadream Oct 31 '18 at 23:25
  • That works. path.Replace(CurrentEnvironment.ContentRootPath, "~/").Replace(@"\", "/"); – Watson Nov 01 '18 at 00:09

0 Answers0