【发布时间】:2018-06-26 22:03:20
【问题描述】:
所以过去一周我一直在尝试构建一个 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");
}
【问题讨论】:
-
要回答这个问题,
Controller上有一个File方法,编译器试图绑定该方法而不是File类。尝试将其更改为StreamReader reader = new StreamReader(System.IO.File.OpenRead(attachmentcsv)); -
.Net 中已经有一些 csv 阅读器,NuGet 上已经有一些更好的阅读器。您这样做是为了好玩,还是更愿意使用现有选项?值得注意的是,基本的 Split() 方法是真正糟糕的 csv 阅读器。性能很差,并且有很多边缘情况会导致它为您创建不良数据。
-
@Dstanley 谢谢!修复了这个问题,虽然它似乎也需要一个连接字符串,但感谢现有的读者
-
@JoelCoehoorn 并不是很有趣,哈哈,作为一个新手,这种方式看起来很简单,但行不通。我会查看作为答案发布的 csv 阅读器。
-
对于未来的问题,请一次问一件事 - “如何解析 CSV - 这是我的代码”(我关闭了这个作为规范答案的副本)或“我得到尝试编写代码时出现此错误”(这本身就可以,但您需要 minimal reproducible example 而不是当前发布的代码)。