c# - Adding a Way To preserve A Comma In A CSV To DataTable Function -


I have a function that is one. Converts a Csv file to Datat. One of the columns I am converting is one area of ​​the name in which there is a comma in them I.e. When converting "Do, John" function, it behaves like 2 different areas due to commas. I need a dateline to place this field, John in the database.

CSV2DataTable (byVal file name string, as in the form of ByVal sepChar string) DataTable dim reader System.IO.StreamReader dim table as new DataTable dim colAdded as in the form of Boolean = false try as opening #in '' a = 0 '' # can read a row and it is divided into tokens, divided by specifying '; Reader.Peek () & gt; reader for input file, and line read by line reader = new System.IO.StreamReader (file name) Do the # Separator Dimension Token string () = System.Text.RegularExpressions .Regex.Split _ (reader.ReadLine (), sepChar) '' # Add column if it is not colAdded for the first line then for each token string as in the token table. Columns Add (Token) Next colAdded = True Else '' # Create a new blank line in the form of DataRow = table.NewRow () fill the dim line '# # New Token Exclamation' Excluded from row - '# DataTable table.Rows.Add To add the row 'I' to # integer = 0 table.Columns.Count as to line 1 (i) token (i) next = '(line) end if the loop return table end if the reader is nothing Then reader Try Close () End End Function

using a Do not SPTIT () function to read your CSV data. Not only the kind of mistake you have made, but it is slow you need a state machine based parser. It will be faster and it will be easy to handle the quote-attached text correctly.

I have an example here:

And there is also a highly respected CSV reader on CodePlex, you can use it:


You will use your code in this way:

  Function DatableFront CSV (String in the form of binline filename) Datatale as Dim Table in the form of new DataTable dim colAdded Boolean = False 'For every record IList (string of) in CSV.FromFile (file name) for' # first or If the column headers are added then each token string is in the form of table.Columns.Add as then not colAdded (token) next token colAdded = true or else the DataRow = table.NewRow table add row to the dim row () I as integer = 0 to table.Columns.Count - 1 row (i) = record (i) Next table. Rows. Add (line) closing if the next record return table expiration function  

If you are using .NET 3.5 or later, then I pull out the column build for each loop (Typed conclusion and using (1) ), but I have to make sure that it will also work with Net 2.0.


Comments