在.NET中,资源(Resources)通常指一些配置、程序集、文件、数据存储等。下面是创建和使用资源的方法:
AppContext
已经不复存在,使用 IHostingEnvironment
API 创建资源,它提供了一个与应用程序运行环境相关的更高级别的API。IHostingEnvironment
实例:IHostingEnvironment _hostingEnvironment = new HostingEnvironment();
string connectionString = _hostingEnvironment.ContentRootPath + "/Data/dbConnection.db";
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
builder.UserName = "username";
builder.Password = "password123";
builder.Encrypt = true;
SqlConnection connection = new SqlConnection(builder.ConnectionString);
WebConfigurationFileMap
获取,从IHostingEnvironment
实例中获取)using System.Web;
using System.Web.Configuration;
var map = _hostingEnvironment.WebRootFileProvider.GetFileMap("images/test-image.jpg");
string filePath = map.PhysicalPath;
// 获取文件对象
using (StreamReader reader = new StreamReader(filePath))
using (FileStream writer = new FileStream(filePath, FileMode.CreateNew))
{
reader.BaseStream.CopyTo(writer);
writer.Close();
}
var config = Configuration.GetSection("custom-sections");
var optionsSection = config["options"];
var sampleOption = optionsSection["sampleOption"];
Console.WriteLine(sampleOption.Value);
示例:创建一个包含特定名称的网页】
IHostingEnvironment _hostingEnvironment = new HostingEnvironment();
string rootDirectory = _hostingEnvironment.ContentRootPath;
// 获取虚拟目录(根据实际需求确定是否需要)
var physicalPath = PhysicalPath(rootDirectory, "customSite");
// 创建 WebProjectBuilder 实例
WebProjectBuilder builder = new WebProjectBuilder(physicalPath, projectPaths =>
{
projectPaths.AddDirectory("App\_Code");
projectPaths.AddDirectory("Models");
projectPaths.AddDirectory("Resources");
projectPaths.AddFromFile("Web.config");
projectPaths.AddFromFile("web\_content/index.chtml");
// ... other project paths...
});
...
上述方法可用于创建和管理各种资源,包括数据库连接、文件(动态文件可通过请求动态生成)、配置文件等。在使用时,要保证资源以安全的方式(加密)存储。此外,在使用资源时要注意防止XSS 和 CSRF 攻击。
领取专属 10元无门槛券
手把手带您无忧上云