473,795 Members | 3,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Importing a CSV file

What is the best way to import the contents of a CSV file into C#
objects?

E.G. a CSV file that looks like this

a1,b1,c1,d1,
a2,b2,c2,d2,
a3,b3,c3,d3

Would be loaded up and then turned into 3 objects

object 1
field1 = a1
field2 = b1
field3 = c1
field4 = d1

object 2
field1 = a2
field2 = b2
field3 = c2
field4 = d2

object 3
field1 = a3
field2 = b3
field3 = c3
field4 = d3

Thanks,

Peter.

Mar 22 '06 #1
1 2056
I would use IO.StreamReader class to open the file, then read it into a
dataTable.
Here is the function that does just that in VB.Net (but it can be easily
converted to C# to suit your needs though :)

To use it, you do something like
Dim dt As DataTable = BuildDataTable( "C:\myTestFile. txt", ",") 'for CSV file
Once you get this data table, you can do whatever you want with it... Each
datarow serves as one object in your question.

'Reading file to datatable
Private Function BuildDataTable( ByVal fileFullPath As String, ByVal
seperator As Char) As DataTable

Dim myTable As DataTable = New DataTable("MyTa ble")
Dim i As Integer
Dim myRow As DataRow
Dim fieldValues As String()
Dim f As IO.File
Dim myReader As IO.StreamReader
Try
'Open file and read first line to determine how many fields
there are.
myReader = f.OpenText(file FullPath)
fieldValues = myReader.ReadLi ne().Split(sepe rator)
'Create data columns accordingly
For i = 0 To fieldValues.Len gth() - 1
myTable.Columns .Add(New DataColumn("Fie ld" & i))
Next
'Adding the first line of data to data table
myRow = myTable.NewRow
For i = 0 To fieldValues.Len gth() - 1
myRow.Item(i) = fieldValues(i). ToString
Next
myTable.Rows.Ad d(myRow)
'Now reading the rest of the data to data table
While myReader.Peek() <> -1
fieldValues = myReader.ReadLi ne().Split(sepe rator)
myRow = myTable.NewRow
For i = 0 To fieldValues.Len gth() - 1
myRow.Item(i) = fieldValues(i). ToString
Next
myTable.Rows.Ad d(myRow)
End While
Catch ex As Exception
MsgBox("Error building datatable: " & ex.Message)
Return New DataTable("Empt y")
Finally
myReader.Close( )
End Try

Return myTable
End Function

Hope this helps.
VHD50.

"BobLaughla nd" wrote:
What is the best way to import the contents of a CSV file into C#
objects?

E.G. a CSV file that looks like this

a1,b1,c1,d1,
a2,b2,c2,d2,
a3,b3,c3,d3

Would be loaded up and then turned into 3 objects

object 1
field1 = a1
field2 = b1
field3 = c1
field4 = d1

object 2
field1 = a2
field2 = b2
field3 = c2
field4 = d2

object 3
field1 = a3
field2 = b3
field3 = c3
field4 = d3

Thanks,

Peter.

Mar 22 '06 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2236
by: Jeff Wagner | last post by:
I am importing a file which contains a persons name (firstName, middleName, etc). If I define a function to do this, how can I use the variables outside of that function? Here is the code: import string def getName(): data = open("enterName.txt")
12
2407
by: qwweeeit | last post by:
The pythonic way of programming requires, as far as I know, to spread a big application in plenty of more manageable scripts, using import or from ... import to connect the various modules. In some cases there is a further complication: module importing through an indirect mechanism, like: exec "from " + xxx + " import *". A part the fact that I have not understood the "real" difference between import and from ... import (or also from......
1
4601
by: Thomas R. Hummel | last post by:
Hello, I am importing a file using BCP, with a format file. It is a fixed-width file, which I am importing into a table that has a column for each field in the file. The columns in my import table are all defined as CHAR. I use it as a staging area to check the data (are dates formatted correctly, etc.) before moving it from there. In one of my files I have six records that contain strange characters (ascii codes of 03 and 02 if I am...
11
3419
by: Grim Reaper | last post by:
I am importing a .csv file into Access that has 37 fields. My problem is that sometimes the last field only has data at the end of the column (it looks like when you import a file into Access, for the last field, it only checks the top few 'cells' to see if there is any data, if not, the field is not imported). How do I 'force' Access to import the field, regardless if there is data in the top of the field or not? For instance, I might...
1
3681
by: sparks | last post by:
I have never done this and wanted to ask people who have what is the best way. One person said import it to excel, then import it into access table. but since this will be done a lot, I am trying to avoid this extra step. can access read in this file directly into a table as append data? thank you very much for any pointers
5
3184
by: dixie | last post by:
If I sent a user an empty database container - dB with no tables and I needed them to import their tables into it and one of their tables was a hidden table with the prefix Usys, is there any way in code I can get that table imported without them having to go to options and show hidden tables and then import it manually? dixie
3
3354
by: mukeshsrivastav | last post by:
dear sir i want to move form excel to access. i have 5 excel file having same formats and fields.now i want to import all data in one access table. importing one file is easy .but importing and appending second file in last of the access table created earlier by importing data. thanks .plz help me.
0
489
by: Alun Jones | last post by:
I'm getting the above error in a dialog box from Visual Studio 2005 when trying to sign an assembly using a PFX file, and would like to know how to resolve the problem. Background: The PFX file has been used for code-signing before (to sign an InfoPath form), so therefore the file contains a valid code-signing key. I have the correct password to the PFX file (because I get a different error
7
1968
by: hg | last post by:
Hi, I have the following problem. I find in a directory hierarchy some files following a certain sets of rules: ..../.../../plugin/name1/name1.py ..... ..../.../../plugin/namen/namen.py
12
6223
by: JMO | last post by:
I can import a csv file with no problem. I can also add columns to the datagrid upon import. I want to be able to start importing at the 3rd row. This will pick up the headers necessary for the datagrid. Once I can get to that point I need some way to be able to add new data only to the new columns that were added. Here is some of my code: //Function For Importing Data From CSV File public DataSet ConnectCSV(string filetable)
0
9672
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.