我有一个ASP.NET Core(1.0-rc1-final(MVC解决方案,我希望在项目中存储一个简单的文本文件,其中包含一个字符串列表,我将其读取到控制器中的字符串数组中。
我应该将此文件存储在项目中的何处,以及如何在控制器中读取这些文件?
在ASP.net 4.x中,我会使用app_data
文件夹并执行类似于的操作
string path = Server.MapPath("~/App_Data/File.txt");
string[] lines = System.IO.File.ReadAllLines(path);
但是Server.MapPath
在ASP.Net Core 1中似乎无效,我也不确定app_data
文件夹是否有效。
我找到了一个简单的解决方案。
首先,您可以在解决方案中的任何位置创建一个文件夹,而不必拘泥于.net 4.x中的"app_data"之类的约定。
在我的场景中,我在项目的根目录下创建了一个名为"data"的文件夹,我把我的txt文件放在那里,并用这个代码将内容读取到字符串数组中
var owners = System.IO.File.ReadAllLines(@"..dataOwners.txt");
您可以在控制器中使用依赖注入获得环境:
using Microsoft.AspNetCore.Hosting;
....
public class HomeController: Controller
{
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env)
{
_env = env;
}
...
然后,您可以在操作中获取wwwroot位置:_env.WebRootPath
var owners = System.IO.File.ReadAllLines(System.IO.Path.Combine(_env.WebRootPath,"File.txt"));
在您的控制器中,您可以对IApplicationEnvironment进行依赖,并将其注入构造函数,然后您可以使用它来建立文件的路径,这样您的文件就可以位于项目中的文件夹中。在下面的示例中,"env"是IApplicationEnvironment 的实例
using Microsoft.Extensions.PlatformAbstractions;
var pathToFile = env.ApplicationBasePath
+ Path.DirectorySeparatorChar.ToString()
+ "yourfolder"
+ Path.DirectorySeparatorChar.ToString()
+ "yourfilename.txt";
string fileContent;
using (StreamReader reader = File.OpenText(pathToFile))
{
fileContent = reader.ReadToEnd();
}
ApplicationBasePath表示applicationRootFolder
请注意,也存在IHostingEnvironment,它有熟悉的.MapPath方法,但它适用于存储在wwwroot文件夹下的内容。您应该只将内容存储在要与http请求一起提供服务的wwwroot文件夹下,因此最好将字符串列表保存在其他文件夹中。
这在本地和IIS上一直适用。
AppDomain.CurrentDomain.BaseDirectory
要访问您的文件,您可以简单地执行以下操作:
import System.IO
...
var owners = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File.txt"))
IApplicationEnvironment
和IRuntimeEnvironment
已于2016/04/26在github上发布公告后删除。
我用这个替换了@JoeAudette的代码
private readonly string pathToFile;
public UsersController(IHostingEnvironment env)
{
pathToFile = env.ContentRootPath
+ Path.DirectorySeparatorChar.ToString()
+ "Data"
+ Path.DirectorySeparatorChar.ToString()
+ "users.json";
}
我的.json
文件位于src/WebApplication/Data/users.json
然后我像一样读取/解析这些数据
private async Task<IEnumerable<User>> GetDataSet()
{
string source = "";
using (StreamReader SourceReader = File.OpenText(pathToFile))
{
source = await SourceReader.ReadToEndAsync();
}
return await Task.FromResult(JsonConvert.DeserializeObject<IEnumerable<User>>(source)));
}
此方法在本地和Azure环境中对我有效。这是从乔在上面的回答中得到的
public static string ReadFile(string FileName)
{
try
{
using (StreamReader reader = File.OpenText(FileName))
{
string fileContent = reader.ReadToEnd();
if (fileContent != null && fileContent != "")
{
return fileContent;
}
}
}
catch (Exception ex)
{
//Log
throw ex;
}
return null;
}
这就是调用方法的方式
string emailContent = ReadFile("./wwwroot/EmailTemplates/UpdateDetails.html");