// 获取当前程序所在路径,并将要创建的文件命名为info.json
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
if (!File.Exists(fp)) // 判断是否已有相同文件
{FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite); fs1.Close();
}
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
File.WriteAllText(fp, JsonConvert.SerializeObject(obj));
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
Object obji = JsonConvert.DeserializeObject
string basePath1 = AppContext.BaseDirectory;
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);
// D:\后端项目\testCore\test.WebApi\bin\Debug\net6.0\
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;namespace AspNetCorePathMapping
{public class HomeController : Controller{private readonly IHostingEnvironment _hostingEnvironment;public HomeController(IHostingEnvironment hostingEnvironment){_hostingEnvironment = hostingEnvironment;}public ActionResult Index(){string webRootPath = _hostingEnvironment.WebRootPath;string contentRootPath = _hostingEnvironment.ContentRootPath;// webRootPath: D:\后端项目\testCore\test.WebApi\wwwroot// contentRootPath: D:\后端项目\testCore\test.WebApireturn Content(webRootPath + "\n" + contentRootPath);}}
}
namespace TestProject.services
{public class ConfigHelper{private static IConfiguration _config;public ConfigHelper(IConfiguration configuration){_config = configuration;}/// /// 读取appsettings.json文件中指定节点信息/// /// /// public static string ReadAppSettings(params string[] sessions){try{if (sessions.Any()){return _config[string.Join(":",sessions)];}}catch{return "";}return "";}/// /// 读取实体信息/// /// /// /// public static List ReadAppSettings(params string[] session){List list = new List();_config.Bind(string.Join(":",session),list);return list;}}
}
var builder = WebApplication.CreateBuilder(args);IConfiguration configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();builder.Services.AddSingleton(new ConfigHelper(configuration));
{"Logging": {"LogLevel": {"Default": "Information","Microsoft.AspNetCore": "Warning"}},"AllowedHosts": "*","Test": {"testStr1": "testvalue1","testStr2": "testvalue2"},
}
string str = ConfigHelper.ReadAppSettings("Test", "testStr1");
上一篇:网站https 问题记录