C# .NET CSVReader过帐文件

C# .NET CSVReader过帐文件,c#,asp.net,.net,asp.net-mvc,C#,Asp.net,.net,Asp.net Mvc,我已经创建了一个CSV解析器,它使用了我在这里能找到的最推荐的nuget,CSVReader。我想我的代码差不多就在那里了,它只是将文件发布到控制器actionmethod,我在上面找不到足够的内容。我得到一个错误: System.IO.FileNotFoundException:'找不到文件'C:\Program Files(x86)\IIS Express\System.Web.HttpPostedFileWrapper' 控制器动作方法: [HttpPost] public

我已经创建了一个CSV解析器,它使用了我在这里能找到的最推荐的nuget,CSVReader。我想我的代码差不多就在那里了,它只是将文件发布到控制器actionmethod,我在上面找不到足够的内容。我得到一个错误:

System.IO.FileNotFoundException:'找不到文件'C:\Program Files(x86)\IIS Express\System.Web.HttpPostedFileWrapper'

控制器动作方法:

    [HttpPost]
    public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
    {
        if (ModelState.IsValid)
        {
            using (CsvReader csv = new CsvReader(new StreamReader(attachmentcsv.ToString()), true))
            {
                csv.Configuration.HasHeaderRecord = true;
                var records = csv.GetRecords<Client>().ToList();

                foreach (var item in records)
                {
                    String Strip = item.homePage.Replace("https://www.", "").Replace("http://www.", "").Replace("https://", "").Replace("http://", "").Replace("www.", "");
                    string[] URLtests = { "https://www." + Strip, "http://www." + Strip, "https://" + Strip, "http://" + Strip };
                    string[] Metric = MajesticFunctions.MajesticChecker(URLtests);
                    var userId = User.Identity.GetUserId();
                    var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
                    var newclient = new Client { clientN = item.clientN, homePage = Metric[0], clientEmail = item.clientEmail, contName = item.contName.First().ToString().ToUpper() + item.contName.Substring(1), monthlyQuota = item.monthlyQuota, TrustFlow = Int32.Parse(Metric[1]), CitationFlow = Int32.Parse(Metric[2]), RI = Int32.Parse(Metric[3]), MJTopicsID = item.MJTopicsID, UserTableID = UserTableID };
                    ViewBag.newdomain = newclient;
                    db.Clients.Add(newclient);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
        }
        return RedirectToAction("Index");
[HttpPost]
public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
{
if(ModelState.IsValid)
{
使用(CsvReader csv=new CsvReader(new StreamReader(attachmentcsv.ToString()),true))
{
csv.Configuration.HasHeaderRecord=true;
var records=csv.GetRecords().ToList();
foreach(记录中的var项目)
{
String Strip=item.homePage.Replace(“https://www.“,”)。替换(”http://www.“,”).Replace(“https:/”,“”)。Replace(“http:/”,“”)。Replace(“www.”,“”);
字符串[]URLtests={”https://www.“+带,”http://www.“+Strip,”https://“+Strip,”http://“+Strip};
string[]Metric=MajesticFunctions.MajesticChecker(URLtests);
var userId=User.Identity.GetUserId();
var UserTableID=db.UserTables.Where(c=>c.applicationserid==userId.First().ID;
var newclient=newclient{clientN=item.clientN,homePage=Metric[0],clientEmail=item.clientEmail,contName=item.contName.First().ToString().ToUpper()+item.contName.Substring(1),monthlyQuota=item.monthlyQuota,TrustFlow=Int32.Parse(Metric[1]),引文flow=Int32.Parse(Metric[2]),RI=Int32.Parse(Metric[3]),MJTopicsID=item.MJTopicsID,UserTableID=UserTableID};
ViewBag.newdomain=newclient;
db.Clients.Add(newclient);
db.SaveChanges();
返回操作(“索引”);
}
}
}
返回操作(“索引”);
查看上载按钮:

@using (Html.BeginForm("CreateBulk", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
<label for="attachment">Select a Csv File</label>
<label class="btn btn-default btn-file">
<input type="file" name="attachmentcsv" id="attachmentcsv" hidden>
</label>
</div>
<button type="submit" class="btn btn-primary">Upload</button>
}
@使用(Html.BeginForm(“CreateBulk”,“Clients”,FormMethod.Post,new{enctype=“multipart/formdata”}))
{
选择一个Csv文件
上传
}
客户机型号:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Linkofy.Models
{
public class Client
{
    public int ID { get; set; }

    [Required]
    [Display(Name = "Client")]
    public string clientN { get; set; }

    [Display(Name = "Website")]
    public string homePage{ get; set; }

    [EmailAddress]
    [Display(Name = "Contact Email")]
    public string clientEmail { get; set; }

    [Display(Name = "Contact Name")]
    public string contName { get; set; }

    [Display(Name = "Monthly")]
    public int monthlyQuota { get; set; }

    [Display(Name = "TF")]
    public int TrustFlow { get; set; }

    [Display(Name = "CF")]
    public int CitationFlow { get; set; }

    [Display(Name = "RIPs")]
    public int RI { get; set; }

    public int? MJTopicsID { get; set; }
    public virtual MJTopics MJTopics { get; set; }

    public int UserTableID { get; set; }
    public virtual UserTable UserTable { get; set; }

    public virtual ICollection<Link> Links { get; set; }
    public virtual ICollection<Status> Statuss { get; set; }
}
}
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
使用System.ComponentModel.DataAnnotations.Schema;
名称空间Linkofy.Models
{
公共类客户端
{
公共int ID{get;set;}
[必需]
[显示(Name=“客户”)]
公共字符串clientN{get;set;}
[显示(Name=“网站”)]
公共字符串主页{get;set;}
[电邮地址]
[显示(Name=“联系电子邮件”)]
公共字符串clientEmail{get;set;}
[显示(Name=“联系人姓名”)]
公共字符串contName{get;set;}
[显示(Name=“每月”)]
public int monthlyQuota{get;set;}
[显示(Name=“TF”)]
公共int信任流{get;set;}
[显示(Name=“CF”)]
公共流{get;set;}
[显示(Name=“RIPs”)]
公共int RI{get;set;}
公共int?MJTopicsID{get;set;}
公共虚拟主题{get;set;}
public int UserTableID{get;set;}
公共虚拟用户表用户表{get;set;}
公共虚拟ICollection链接{get;set;}
公共虚拟ICollection状态{get;set;}
}
}
您应该查看:

但在查看您的代码时,我想指出以下几点:

隔离
attachmentcsv.ToString()
行,这似乎返回了
System.Web.HttpPostedFileWrapper
的类型,这就是为什么要将此字符串附加到文件位置

我相信您可能正在寻找
附件csv.FileName
,根据类型()的文档

获取客户端上文件的完全限定名

我不确定您使用的是框架还是ASP的核心版本,但我相信在ASP的框架版本中,访问上传文件的“正确”方式(如链接的答案所示)是通过
请求
对象:
请求.Files

在ASP的核心版本中,您可以使用IFileForm,如下所示:

[HttpPost(“上传文件”)]
公共异步任务发布(列表文件)
{
long size=files.Sum(f=>f.Length);
//临时位置中文件的完整路径
var filePath=Path.GetTempFileName();
foreach(文件中的var formFile)
{
如果(formFile.Length>0)
{
使用(var stream=newfilestream(filePath,FileMode.Create))
{
等待formFile.CopyToAsync(流);
}
}
}
//处理上载的文件
//未经验证,请勿依赖或信任FileName属性。
返回Ok(新的{count=files.count,size,filePath});
}

希望这有帮助

哇,这是一个多么好的书面回答!谢谢。因此,如果我创建一个iformfile的模型绑定,用额外的几行代码模仿客户端模型,它会按照我的预期工作吗。通过var records=csv.GetRecords().ToList();iform文件最初将其绑定到模型,以便我可以将其保存到数据库?此外,我正在使用MVC5中的MVC5,类似这样的东西应该可以导入您的文件()似乎能够阅读该文件!非常感谢,最后一个快速问题被卡在Id列上,说它在文件中找不到,我如何让它忽略它?它说ireaderconfiguration不包含willthrowonmissingfields的定义,可能库已经更改,明天将进一步研究它,如果ot发布问题,谢谢您的时间!
[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}