How to Read Cvs File That Is Missing a Column in C

One thing that you lot should come to grips with is that those Filexxxx methods are all just officially and formally deprecated. When using them, Intellisense pops upwardly with:

...The My feature gives y'all better productivity and performance in file I/O operations than FileOpen. For more data, run across Microsoft.VisualBasic.FileIO.FileSystem.

They are talking about My.Computer.FileSystem but there are some fifty-fifty more useful NET methods.

The mail service doesnt reveal how the data will be stored, just if it is an array of any sort and/or a structure, those are at least suboptimal if not as well outdated. This will shop it in a class so that the numeric information can be stored as numbers and a List volition be used in place of an array.

I made a quick file similar to yours with some random data: {"CustName", "Phone", "UserName", "Product", "Cost", "Toll", "Profit", "SaleDate", "RefCode"}:

  • The CustName is present 70% of the fourth dimension
  • The username is never present
  • The RefCode is present 30% of the fourth dimension
  • I added a SaleDate to illustrate that information conversion

Ziggy Aurantium,132-5562,,Cat Food,8.26,9.95,1.69,08/04/2016,
Catrina Caison,899-8599,,Knife Sharpener,4.95,6.68,1.73,10/12/2016,X-873-W3
,784-4182,,Vapor Compressor,11.02,12.53,ane.51,09/12/2016,

Code to Parse the CSV

Note: this is a bad way to parse a CSV. There are lots of bug that tin arise doing it this way; plus information technology takes more than code. It is presented because information technology is a simple fashion to not take to deal with the missing fields. See The Right Manner

          ' grade/class level var: Private SalesItems As Listing(Of SaleItem)                  

SaleItem is a simple course to store the elements you intendance about. SalesItems is a collection which can store only SaleItem objects. The properties in that class allow Toll and Toll to be stored as Decimal and the date as a DateTime.

          ' temp var Dim detail As SaleItem ' create the drove SalesItems = New Listing(Of SaleItem)      ' load the information....all of information technology Dim data = File.ReadAllLines("C:\Temp\custdata.csv")  ' parse data lines  ' Start at 1 to skip a Header For n As Int32 = 0 To data.Length - 1     Dim split = information(n).Split up(","c)      ' bank check if it is a good line     If dissever.Length = 9 Then         ' create a new detail         item = New SaleItem         ' store SOME information to it         item.CustName = split up(0)         item.Phone = split(i)         ' dont care anout user name (two)         particular.Product = divide(3)         ' convert numbers         item.Price = Convert.ToDecimal(split(4))         item.Cost = Convert.ToDecimal(split(5))         ' dont employ the Turn a profit, summate it in the grade (vi)          ' convert date         detail.SaleDate = Catechumen.ToDateTime(split(7))          ' ignore nonexistant RefCode (eight)          ' add together new item to drove         ' a Listing sizes itself every bit needed!         SalesItems.Add together(item)     Else         ' To Practice: brand note of a bad line format     End If Next  ' show in DGV for blessing/debugging dgvMem.DataSource = SalesItems                  

Result: enter image description here

Notes
It is by and large a bad idea to store something which can be just calculated. So the Profit property is:

          Public ReadOnly Holding Turn a profit As Decimal     Get         Return (Cost - Price)     End Get Terminate Property                  

Information technology can never be "stale" if the cost or cost is updated.

Equally shown, using the resulting drove tin can be displayed to the user very easily. Given a DataSource, the DataGridView will create the columns and populate the rows.

The Correct Way

Cord.Carve up(c) is a very bad idea considering if the product is: "Hose, Pocket-size Green" it volition chop that up and treat information technology as 2 fields. In that location are a number of tools which will do almost all the work for you:

  1. Read the file
  2. Parse the lines
  3. Map the CSV information to a class
  4. convert the text into the proper data type
  5. create an economical collecton

Aside from the class, all the above could be done in just a few lines using CSVHelper:

          Individual CustData As List(Of SaleItem) ... Using sr Equally New StreamReader("C:\Temp\custdata.csv", Faux),      csv = New CsvReader(sr)     csv.Configuration.HasHeaderRecord = True      CustData = csv.GetRecords(Of SaleItem)().ToList() Stop Using                  

2 or three lines of code to read, parse, and create a drove of 250 items.

Even if you want to do it manually for some reason, CSVHelper can help. Rather than create a List(Of SaleItem) for you, you can use it to read and parse the data:

          ... like above csv.Configuration.HasHeaderRecord = True Do Until csv.Read() = False     For n Equally Int32 = 0 To csv.Parser.FieldCount - one         DoSomethingWith(csv.GetField(n))     Next Loop                  

This will return the fields to you ane by one. Information technology wont catechumen whatsoever dates or prices, but it wont choke on missing data elements either.

Resources

  • Five Minute Intro To Classes and Lists
  • CSVHelper
  • Class vs Structure
    • Eric Lippert's Thoughts on the matter
  • The File Grade has gobs of useful methods

edwardsintle1976.blogspot.com

Source: https://stackoverflow.com/questions/41108845/reading-csv-file-some-missing-columns

0 Response to "How to Read Cvs File That Is Missing a Column in C"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel