Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从MockRepository.cs中读取文件-appEnvironment不存在_C#_Asp.net_Visual Studio_Model View Controller - Fatal编程技术网

C# 如何从MockRepository.cs中读取文件-appEnvironment不存在

C# 如何从MockRepository.cs中读取文件-appEnvironment不存在,c#,asp.net,visual-studio,model-view-controller,C#,Asp.net,Visual Studio,Model View Controller,我有Visual Studio 2017。我正在尝试将我的csv文件读入我的数据库以进行初始化。我正在修改Bethany's Pie Shop的Node Repo培训,创建列表页面的过程已经进行了一半,演示了如何在培训中创建域。在培训中,他们使用静态列表信息初始化数据库,我想使用我的csv文件。但是我读文件有困难。我看了看,但它没有帮我修好。因此,我正在尝试的建议,然后将添加路径到我的csv文件之后。我对MVC网页等非常陌生,所以我很难理解如何将最后一个示例应用到我的代码中 我有点困惑Appen

我有Visual Studio 2017。我正在尝试将我的csv文件读入我的数据库以进行初始化。我正在修改Bethany's Pie Shop的Node Repo培训,创建列表页面的过程已经进行了一半,演示了如何在培训中创建域。在培训中,他们使用静态列表信息初始化数据库,我想使用我的csv文件。但是我读文件有困难。我看了看,但它没有帮我修好。因此,我正在尝试的建议,然后将添加路径到我的csv文件之后。我对MVC网页等非常陌生,所以我很难理解如何将最后一个示例应用到我的代码中

我有点困惑AppenEnvironment将如何为我的文件提供根路径,我将使用StreamReader

现在我明白了

appEnvironment在当前上下文中不存在,我将尝试在Get()中返回它

我知道我应该在那里返回IEnumerable,但是如何获得我的根路径?使用appenvironment的示例返回以下内容:

FolderScanner scanner = new FolderScanner(_hostEnvironment.WebRootPath);
return scanner.scan();
我没有折叠扫描仪。也许这是微软的事?我更像是一个C++/php程序员,所以我并不总是确定。恕我直言,我正在努力学习(对我来说)微软技术这一全新的世界。这就是我目前所拥有的,我为在我的MockNodeRepository.cs中包含大量信息而道歉:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using System.IO;
using System.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
//using Microsoft.AspNetCore.Hosting.Internal.HostingEnvironment;
using Microsoft.AspNetCore.Http;

namespace CATV_Dashboard_Node_Viewer.Models
{
    public class MockNodeRepository : INodeRepository
    {
        private List<Node> _nodes;
        private string csvFile;
        //private string csvFile = HttpContext.Current.Server.MapPath("~/App_Data/Data.csv");//System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~htm/external/Data.csv")); //need to check path here

        private string rootPath;
        public string CsvFile { get => csvFile; set => csvFile = rootPath + "/App_Data/Data.csv"; }

        public IEnumerable<string> Get()
        {
            return appEnvironment.ApplicationName; //appEnvironment doesn't exist in current contest
        }

        private readonly IHostingEnvironment _appEnvironment;

        public MockNodeRepository(IHostingEnvironment appEnvironment)
        {
            _appEnvironment = appEnvironment;
        }
        public MockNodeRepository()
        {
            if(_nodes == null)
            {
                InitializeNodes();
            }
        }
        private void InitializeNodes()
        {
            _nodes = ConvertCSVtoList(CsvFile);
        }

        private  List<Node> ConvertCSVtoList(string strFilePath)
        {
            List<Node> nodes = new List<Node>();
            StreamReader sr = new StreamReader(strFilePath);
            string[] headers = sr.ReadLine().Split(','); //remove header from Stream
            //get each row of csv and convert to node add to List
            while(!sr.EndOfStream)
            {
                string[] rows = sr.ReadLine().Split(',');
                nodes.Add( new Node { NodeID = rows[0], Color = rows[1], CMTSName = rows[3], PercentDown = Convert.ToInt32(rows[4]), Count = Convert.ToInt32(rows[5]) });
            }
            return nodes;
        }

        public IEnumerable<Node> GetAllNodes()
        {
            throw new NotImplementedException();
        }

        public Node GetNodeByID(string nodeId)
        {
            throw new NotImplementedException();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用系统数据;
使用System.IO;
使用System.Web;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.Extensions.Hosting;
//使用Microsoft.AspNetCore.Hosting.Internal.HostingEnvironment;
使用Microsoft.AspNetCore.Http;
名称空间CATV_仪表板_节点_查看器.Models
{
公共类MockNodeRepository:INodeRepository
{
私有列表节点;
私有字符串csvFile;
//私有字符串csvFile=HttpContext.Current.Server.MapPath(“~/App_Data/Data.csv”);//System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath(“~htm/external/Data.csv”);//需要在此处检查路径
私有字符串根路径;
公共字符串CsvFile{get=>CsvFile;set=>CsvFile=rootPath+“/App_Data/Data.csv”;}
公共IEnumerable Get()
{
return appEnvironment.ApplicationName;//当前竞赛中不存在appEnvironment
}
私人只读IHostingEnvironment\u appEnvironment;
公共模拟存储(IHostingEnvironment appEnvironment)
{
_外观环境=外观环境;
}
公共MockNodeRepository()
{
如果(_nodes==null)
{
InitializeNodes();
}
}
私有void InitializeNodes()
{
_节点=ConvertCSVtoList(CsvFile);
}
私有列表ConvertCSVtoList(字符串strFilePath)
{
列表节点=新列表();
StreamReader sr=新的StreamReader(strFilePath);
string[]headers=sr.ReadLine().Split(',');//从流中删除头
//获取csv的每一行并转换为节点添加到列表
而(!sr.EndOfStream)
{
string[]rows=sr.ReadLine().Split(',');
添加(新节点{NodeID=rows[0],Color=rows[1],CMTSName=rows[3],PercentDown=Convert.ToInt32(rows[4]),Count=Convert.ToInt32(rows[5]);
}
返回节点;
}
公共IEnumerable GetAllNodes()
{
抛出新的NotImplementedException();
}
公共节点GetNodeByID(字符串nodeId)
{
抛出新的NotImplementedException();
}
}
}

我保留了一些stateheloper.cs来存储我的环境。 我在startup.cs中捕获并存储环境。 然后我使用下面的streamreader来编写文件。应该是一样的

startup.cs-商店ihostingenvironment

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    Utilities.StateHelper.HostingEnvironment = env;
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseMvcWithDefaultRoute();
}
StateHelper.cs

public static class StateHelper
{
    public static IHostingEnvironment HostingEnvironment { get; set; } = null;
}
使用streamreader在操作后处理程序的控制器中写入文件

string fileName = Path.GetFileName(formFile.FileName);
filePath = Path.Combine(Utilities.StateHelper.HostingEnvironment.WebRootPath, "content", fileName );

using (var stream = new FileStream(filePath, FileMode.Create))
{
await formFile.CopyToAsync(stream);
}

快乐编码…

您的测试应该与您的web应用程序放在一个单独的项目中。执行测试时,线束作为独立控制台应用程序运行。该文件应作为测试项目的内容驻留,您可以使用类似于
AppDomain.CurrentDomain.BaseDirectory的内容获取执行测试的当前目录,谢谢您提供的信息。我没有测试。MockRepository是一个有趣的名字。您仍然可以使用AppDomain.CurrentDomain.BaseDirectory
并获得相同的结果。只需获取应用程序正在运行的基本目录(asp.net core只是一个控制台应用程序)并将文件夹位置附加到引用文件中。