所以我上周一直在尝试构建一个CSV解析器,我尝试过Oledb阅读器,但似乎我必须有一个链接到某个文件夹的连接字符串,而我想要一个动态位置。我现在已经建立了这个,看起来几乎就在第4行:
StreamReader reader = new StreamReader(File.OpenRead(attachmentcsv));
文件下划线说
Controller.File(byte []。string)是一种在当前上下文中无效的方法
我认为这意味着我需要把它放在一个函数中,虽然它是我唯一会使用它并且不想真正想要的,因为我在使用函数时还有其他选择吗?
[HttpPost]
public ActionResult CreateBulk(HttpPostedFileBase attachmentcsv)
{
StreamReader reader = new StreamReader(File.OpenRead(attachmentcsv));
List<string> clientN = new List<String>();
List<string> homePage = new List<String>();
List<string> clientEmail = new List<String>();
List<string> contName = new List<String>();
List<string> monthlyQuota = new List<String>();
List<string> MJTopicsID = new List<String>();
//string vara1, vara2, vara3, vara4;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (!String.IsNullOrWhiteSpace(line))
{
string[] values = line.Split(',');
if (values.Length >= 4)
{
clientN.Add(values[0]);
homePage.Add(values[1]);
clientEmail.Add(values[2]);
contName.Add(values[3]);
monthlyQuota.Add(values[4]);
MJTopicsID.Add(values[5]);
}
}
}
string[] AddclientN = clientN.ToArray();
string[] AddhomePage = homePage.ToArray();
string[] AddclientEmail = clientEmail.ToArray();
string[] AddcontName = contName.ToArray();
string[] AddmonthlyQuota = contName.ToArray();
string[] AddMJTopicsID = contName.ToArray();
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
for (int i = 0; i < AddclientN.Length; i++)
{
String Strip = AddhomePage[i].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 newclient = new Client { clientN = AddclientN[i], homePage = Metric[0], clientEmail = AddclientEmail[i], contName = AddcontName[i].First().ToString().ToUpper() + AddcontName[i].Substring(1), monthlyQuota = Int32.Parse(AddmonthlyQuota[i]), TrustFlow = Int32.Parse(Metric[1]), CitationFlow = Int32.Parse(Metric[2]), RI = Int32.Parse(Metric[3]), MJTopicsID = Int32.Parse(AddMJTopicsID[i]), UserTableID = UserTableID };
ViewBag.newdomain = newclient;
db.Clients.Add(newclient);
db.SaveChanges();
}
return RedirectToAction("Index");
}
答案 0 :(得分:4)
你不应该重新发明轮子。 您可以尝试CSVHelper库https://joshclose.github.io/CsvHelper/
一行代码可以实现您在多行中尝试的内容:
var records = csv.GetRecords<dynamic>();
您可以找到文档here。