Search code examples
c#asp.net.netasp.net-mvccsvhelper

.NET CSV Uploader Allow Nulls


I've put together a CSV importer which I assume works, though I get this error, how do I allow this column to be null so when it adds it to the table it automatically sets the ID? I've tried:

csv.Configuration.WillThrowOnMissingFields = false;

but it doesn't recognise it, this is the error I get when attempting to upload:

CsvHelper.ValidationException: 'Header matching ['ID'] names at index 0 was not found. If you are expecting some headers to be missing and want to ignore this validation, set the configuration HeaderValidated to null. You can also change the functionality to do something else, like logging the issue.'

    [HttpPost]
    [ActionName("CreateBulk")]
    public ActionResult CreateBulkUpload()
    {
        object db;
        var file = Request.Files["attachmentcsv"];
        using (var csv = new CsvReader(new StreamReader(file.InputStream), true))
        {
            var records = csv.GetRecords<Client>().ToList();
            foreach (var item in records)
            {
                var 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.GetHashCode();
                var UserTableID = 1;

                var newclient = new Client

                {
                    clientN = item.clientN,
                    homePage = Metric[0],
                    clientEmail = item.clientEmail,
                    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;
                return RedirectToAction("Index");
            }
        }
        return RedirectToAction("Index");

    }

Solution

  • Did you try out the suggestion mentioned in the error message? like this?

     csv.configuration.HeaderValidated = null;