【发布时间】:2015-04-20 04:22:58
【问题描述】:
我知道以前有人问过这个问题,并且我已尽力找到可以帮助我解决问题的答案 - 但没有成功。我为重复的问题道歉,但我希望你仍然想帮助我。
提前致谢!
我已经制定了一个解决方案,可以将 csv 文件上传到我的 sql 数据库中。当我运行代码时,选择文件并按“上传”我收到以下错误:“输入字符串格式不正确。”
错误在我的控制器中被抛出; LearningNumbers.LearningNumberId = int.Parse(values[0]);
我的 CSV
LearningNumberId;Note;Activity;Price
1;Node1;her er node 1;22
2;Node1;her er node 2;33
我的模特:
namespace MTH_SQL.Model
{
public class LearningNumberRecord
{
[Key]
public int LearningNumberId { get; set; }
public string Note { get; set; }
public string Activity { get; set; }
public int Price { get; set; }
}
}
我的控制器:
namespace MTHoejgaard.Controllers
{
public class HomeController : Controller
{
private MTHoejgaardContext db = new MTHoejgaardContext();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase File)
{
if (File != null && File.ContentLength > 0)
{
StreamReader csvReader = new StreamReader(File.InputStream);
{
string inputLine = "";
while ((inputLine = csvReader.ReadLine()) != null)
{
string[] values = inputLine.Split(new Char[] { ';' });
LearningNumberRecord LearningNumbers = new LearningNumberRecord();
LearningNumbers.LearningNumberId = int.Parse(values[0]); // <-- IT THROWS THE ERROR HERE
LearningNumbers.Note = values[1];
LearningNumbers.Activity = values[2];
LearningNumbers.Price = int.Parse(values[3]);
db.LearningNumbers.Add(LearningNumbers);
db.SaveChanges();
}
csvReader.Close();
}
}
return RedirectToAction("Index");
}
}
我的观点:
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="File" id="File" />
<input type="submit" name="Submit" value="Upload" />
<span>@ViewBag.Message</span>
}
【问题讨论】:
-
我猜如果你调试你的代码,你会在一分钟内找到答案。从 CSV 文件中删除第一行 - 或 - 在解析文件时跳转第一行是否有帮助?
-
我确实尝试过调试它,但我还有很多东西要学,所以我可能错过了。是的 - 它有助于删除第一行或跳过它!谢谢!
标签: c# asp.net asp.net-mvc parsing parseint