I use this code to load views from embedded resources. My main purpose is to load from different assemblies too. Sorry if it's duplicate but I couldn't find my answer.
using SecondApp.Controllers;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
namespace PathProviderSample
{
public class EmbeddedVirtualFile : VirtualFile
{
public EmbeddedVirtualFile(string virtualPath)
: base(virtualPath)
{
}
internal static string GetResourceName(string virtualPath)
{
if (!virtualPath.Contains("/Views/"))
{
return null;
}
var resourcename = virtualPath
.Substring(virtualPath.IndexOf("Views/"))
.Replace("Views/", "SecondApp.Views.")
.Replace("/", ".");
return resourcename;
}
public override Stream Open()
{
Assembly assembly = typeof(TestController).Assembly;
var resourcename = GetResourceName(this.VirtualPath);
return assembly.GetManifestResourceStream(resourcename);
}
}
public class Vpp : VirtualPathProvider
{
private bool ResourceFileExists(string virtualPath)
{
Assembly assembly = typeof(TestController).Assembly;
var resourcename = EmbeddedVirtualFile.GetResourceName(virtualPath);
var result = resourcename != null && assembly.GetManifestResourceNames().Contains(resourcename);
return result;
}
public override bool FileExists(string virtualPath)
{
return base.FileExists(virtualPath) || ResourceFileExists(virtualPath);
}
public override VirtualFile GetFile(string virtualPath)
{
if (!base.FileExists(virtualPath))
{
return new EmbeddedVirtualFile(virtualPath);
}
else
{
return base.GetFile(virtualPath);
}
}
}
}
It loads views from its own assembly but when I request a view from other project (other dll) it cannot find the view .
embedded in main dll : http://localhost:49892/Home/Index2 // it works embedded in other dll : http://localhost:49892/Test/Index // cannot find