我有一个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(@"..\data\Owners.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文件夹下的内容,因此最好将字符串列表保存在不同的文件夹中。
您可以在控制器中获取具有依赖注入的环境:
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
和IRuntimeEnvironment
已于2016/04/26在announcement on 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 = OpenText(pathToFile))
{
source = await SourceReader.ReadToEndAsync();
}
return await Task.FromResult(JsonConvert.DeserializeObject<IEnumerable<User>>(source)));
}
这在本地和IIS上一直对我有用。
AppDomain.CurrentDomain.BaseDirectory
要访问您的文件,您只需执行以下操作:
import System.IO
...
var owners = File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "File.txt"))
此方法适用于本地和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");