C# 如何使用MVC仅更新数据库中.csv文件中的新记录
我已经编写了使用MVC在数据库中上传.csv文件的代码。如何仅上载新记录而忽略现有记录C# 如何使用MVC仅更新数据库中.csv文件中的新记录,c#,asp.net-mvc,C#,Asp.net Mvc,我已经编写了使用MVC在数据库中上传.csv文件的代码。如何仅上载新记录而忽略现有记录 { [HandleError] public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(HttpPosted
{
[HandleError]
public class HomeController : Controller {
public ActionResult Index() {
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase FileUpload) {
// Set up DataTable place holder
DataTable dt = new DataTable();
//check we have a file
if (FileUpload.ContentLength > 0) {
//Workout our file path
string fileName = Path.GetFileName(FileUpload.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
//Try and upload
try {
FileUpload.SaveAs(path);
//Process the CSV file and capture the results to our DataTable place holder
dt = ProcessCSV(path);
//Process the DataTable and capture the results to our SQL Bulk copy
ViewData["Feedback"] = ProcessBulkCopy(dt);
}
catch (Exception ex) {
//Catch errors
ViewData["Feedback"] = ex.Message;
}
}
else {
//Catch errors
ViewData["Feedback"] = "Please select a file";
}
//Tidy up
dt.Dispose();
return View("Index", ViewData["Feedback"]);
}
/// <summary>
/// Process the file supplied and process the CSV to a dynamic datatable
/// </summary>
/// <param name="fileName">String</param>
/// <returns>DataTable</returns>
private static DataTable ProcessCSV(string fileName) {
//Set up our variables
string Feedback = string.Empty;
string line = string.Empty;
string[] strArray;
DataTable dt = new DataTable();
DataRow row;
// work out where we should split on comma, but not in a sentance
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
//Set the filename in to our stream
StreamReader sr = new StreamReader(fileName);
//Read the first line and split the string at , with our regular express in to an array
line = sr.ReadLine();
strArray = r.Split(line);
//For each item in the new split array, dynamically builds our Data columns. Save us having to worry about it.
Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
//Read each line in the CVS file until it's empty
while ((line = sr.ReadLine()) != null) {
row = dt.NewRow();
//add our current value to our data row
row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}
//Tidy Streameader up
sr.Dispose();
//return a the new DataTable
return dt;
}
/// <summary>
/// Take the DataTable and using WriteToServer(DataTable) send it all to the database table "BulkImportDetails" in one go
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>String</returns>
private static String ProcessBulkCopy(DataTable dt) {
string Feedback = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
//make our connection and dispose at the end
using( SqlConnection conn = new SqlConnection(connString)) {
//make our command and dispose at the end
using (var copy = new SqlBulkCopy(conn)) {
//Open our connection
conn.Open();
///Set target table and tell the number of rows
copy.DestinationTableName = "BulkImportDetails";
copy.BatchSize = dt.Rows.Count;
try {
//Send it to the server
copy.WriteToServer(dt);
Feedback = "Upload complete";
}
catch (Exception ex) {
Feedback = ex.Message;
}
}
}
return Feedback;
}
public ActionResult About() {
return View();
}
}
}
{
[手机错误]
公共类HomeController:控制器{
公共行动结果索引(){
返回视图();
}
[HttpPost]
公共操作结果索引(HttpPostedFileBase文件上载){
//设置DataTablePlaceHolder
DataTable dt=新的DataTable();
//检查一下我们有一个文件
如果(FileUpload.ContentLength>0){
//计算我们的文件路径
string fileName=Path.GetFileName(FileUpload.fileName);
字符串路径=path.Combine(Server.MapPath(“~/App\u Data/uploads”),文件名);
//尝试并上传
试一试{
FileUpload.SaveAs(路径);
//处理CSV文件并将结果捕获到我们的DataTable place holder
dt=ProcessCSV(路径);
//处理DataTable并将结果捕获到SQL大容量拷贝中
ViewData[“反馈”]=ProcessBulkCopy(dt);
}
捕获(例外情况除外){
//捕捉错误
ViewData[“反馈”]=例如消息;
}
}
否则{
//捕捉错误
ViewData[“反馈”]=“请选择一个文件”;
}
//收拾
dt.Dispose();
返回视图(“索引”,视图数据[“反馈]);
}
///
///处理提供的文件并将CSV处理为动态数据表
///
///串
///数据表
私有静态数据表ProcessCSV(字符串文件名){
//设置我们的变量
字符串反馈=string.Empty;
string line=string.Empty;
字符串[]strArray;
DataTable dt=新的DataTable();
数据行;
//找出我们应该用逗号分开的地方,但不要用句号
正则表达式r=新正则表达式(“,(?=(?:[^\“]*\”[^\“]*\”*(?![^\“]*\”));
//在我们的流中设置文件名
StreamReader sr=新的StreamReader(文件名);
//读取第一行并在处拆分字符串,并将正则表达式放入数组中
line=sr.ReadLine();
strArray=r.Split(直线);
//对于新拆分数组中的每个项目,动态构建数据列。省去我们的顾虑。
ForEach(strArray,s=>dt.Columns.Add(newdatacolumn());
//读取CVS文件中的每一行,直到其为空
而((line=sr.ReadLine())!=null){
row=dt.NewRow();
//将当前值添加到数据行
row.ItemArray=r.Split(行);
dt.行。添加(行);
}
//整理拖缆机
高级处置();
//返回一个新的数据表
返回dt;
}
///
///获取DataTable并使用WriteToServer(DataTable)一次性将其全部发送到数据库表“BulkImportDetails”
///
///数据表
///串
私有静态字符串ProcessBulkCopy(数据表dt){
字符串反馈=string.Empty;
string connString=ConfigurationManager.ConnectionString[“DataBaseConnectionString”]。ConnectionString;
//建立我们的连接并在最后处理
使用(SqlConnection conn=newsqlconnection(connString)){
//让我们的命令和处置在最后
使用(var copy=new SqlBulkCopy(conn)){
//打开我们的连接
conn.Open();
///设置目标表并告诉行数
copy.DestinationTableName=“BulkImportDetails”;
copy.BatchSize=dt.Rows.Count;
试一试{
//将其发送到服务器
copy.WriteToServer(dt);
反馈=“上传完成”;
}
捕获(例外情况除外){
反馈=例如消息;
}
}
}
反馈;
}
关于()的公共行动结果{
返回视图();
}
}
}
您能为相关语言添加一个标记吗?行是新的吗?你有什么独特的标识数据吗?我认为最快的方法是创建一个只用于上载的表,然后选择新的项并将其插入目标表中。但我应该编写什么代码来选择新的项并将其插入表中?这取决于如何唯一地标识行。他们有身份证之类的东西吗?您的csv看起来怎么样?csv有3列:ID、名称和DOB………我已将PK放入数据库表中,因此现在无法插入相同的记录。