Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
I need to read CSV in C# without using external libraries! the example below i found uses external libraries! is it possible to read CSV in C# without using external libraries??? Help!
 

using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
    // open the file "data.csv" which is a CSV file with headers
    using (CsvReader csv =
           new CsvReader(new StreamReader("data.csv"), true))
    {
        int fieldCount = csv.FieldCount;
 
        string[] headers = csv.GetFieldHeaders();
        while (csv.ReadNextRecord())
        {
            for (int i = 0; i < fieldCount; i++)
                Console.Write(string.Format("{0} = {1};",
                              headers[i], csv[i]));
            Console.WriteLine();
        }
    }
}
Posted 23-Jul-13 18:02pm
Comments
MuhammadUsman1 at 24-Jul-13 0:39am
   
I add solution check it, you can read all data easily and perform required action accordingly.
ThePhantomUpvoter at 24-Jul-13 10:17am
   
"is it possible to read CSV in C# without using external libraries?", yes, yes it is.
"Help!", help with what? You have not said anything about what the problem is that you have yet.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

0) Split won't work in many cases
 
1) Rive[^] instead
  Permalink  
Comments
lukeer at 24-Jul-13 2:07am
   
On one occasion, I would have needed this. I don't recall when or where or how I solved it. But next time I have your bookmark. Thanks.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

Try this 
FileUpload1.SaveAs(Server.MapPath("~/tmpdir/") + FileUpload1.FileName);
System.IO.StreamReader myFile = new System.IO.StreamReader(Server.MapPath("~/tmpdir/")    + FileUpload1.FileName);
string myString = myFile.ReadToEnd();
myFile.Close();
string[] lines = myString.Split(new string[] { Environment.NewLine },      StringSplitOptions.None);
 
foreach (string line in lines)
 {
     if (line != "")
      {
          string[] columns = line.Split(',');
 
          //Upload to your DB with your indexes

      }
     else
      {
 
      }
}
  Permalink  
Comments
kesav prakash at 24-Jul-13 1:39am
   
ya, first it splits the lines and commas??
 
if u don't need this then what's ur expected output??
lukeer at 25-Jul-13 3:11am
   
Yes, you're right. I totally missed the myString.Split() section.
kesav prakash at 25-Jul-13 7:22am
   
great you are welcome.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

Just include System.IO on top and Enjoy.
That is
using System.IO;
Input:(CSV file)
SN	NAME	ADDRESS
1	ram	ktm
2	hari	pkh
Output:
 
SN=1;NAME=ram;ADDRESS=ktm;
SN=2;NAME=hari;ADDRESS=pkh;
Code:
static void Main(string[] args)
   {
       bool isheader = true;
       var reader = new StreamReader(File.OpenRead(@"test.csv"));
       List<string> headers = new List<string>();
 
       while (!reader.EndOfStream)
       {
           var line = reader.ReadLine();
           var values = line.Split(',');
 
           if (isheader)
           {
               isheader = false;
               headers = values.ToList();
           }
           else
           {
             int i=0;
             for (i = 0; i < values.Length; i++)
            {
            Console.Write(string.Format("{0} = {1};", headers[i], values[i]));
 
            }
            Console.WriteLine();
 
           }
      }
   }
  Permalink  
v4
Comments
Hawkeye101 at 24-Jul-13 1:02am
   
Diddnt work mate!
This is my csv format!
 
USD,125.49,132
CAD,124.47,135.98
BHD,325.84,686.98
DKK,21.72,23.84
SEK,15.7,16.75
CHF,134.24,147.11
JPY,1.5493,1.6625
KWD,417.01,934.14
ZAR,11.14,28.18
NOK,21.24,23.35
HKD,15.97,17.06
OMR,316.59,670.88
QAR,33.76,71.14
SAR,27.78,58.62
AED,33.02,70.52
NZD,100.63,109.81
SGD,85.37,89.5
INR,0,3.0896
MYR,39.33,85.3
GBP,203.03,215.54
AUD,129.59,138.96
THB,3.3,7.16
BND,99.22,209.26
EUR,164.59,175.44
JOD,158.81,344.08
CNY,17.38,21.43
Adhikari Surendra at 24-Jul-13 1:04am
   
then what is your expected output?
did you want to display same as of your csv line by line ??
and discription of "USD,125.49,132" (meaning) may be helpful.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hi Hawkeye101399 try following code. with out any external library.
 
 
//Add namespace
using System.IO;
//Read file 
                string[] FileLines = File.ReadAllLines(Environment.SpecialFolder.Desktop + "\\yourfile.csv");
                //know all data is imported in array FileLines
                bool header = false;
                foreach (string nextline in FileLines)
                {
                    // if line empty continue itration
                    if (string.IsNullOrEmpty(nextline))
                        continue;
                    #region On way
                    // declare bool var outside loop and find header
                    if (!header)
                    {
                        string[] allcolumns = nextline.Split(',');
                        //your all columns or header infor will be here 
                        //TODO: what you want
                        header = true;
                    }
                    else
                    {
                        //your data line
                        string[] alldatacolumns = nextline.Split(',');
                        //TODO: what you want,

                    } 
                    #endregion
 
                    #region other way
 
                    //you make sure your first line is header then try this
                    string[] alldata = nextline.Split(',');
                    //if it will be first line then it'll be header other wise datarow. 
                    #endregion
 
                    
                }
 

  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Try Splitting them.
Lets say we have Csv file that contains the folowing:
1,"One"
2,"Two"
3,"Three"
 
VB
 
Sub read()
        Using m_StreamReader As New StreamReader("C:\myCsv.Csv")
 
            While m_StreamReader.Peek >= 0
                Dim m_Str As String = m_StreamReader.ReadLine
                Dim m_Splitted As String() = m_Str.Split(New Char() {","})
                Console.WriteLine(String.Format("{0}={1}", m_Splitted(0), m_Splitted(1)))
            End While
        End Using
End Sub
 
 
C#
 
public static void read()
	{
		using (StreamReader m_StreamReader = new StreamReader("C:\\myCsv.Csv")) {
 
			while (m_StreamReader.Peek >= 0) {
				string m_Str = m_StreamReader.ReadLine;
				string[] m_Splitted = m_Str.Split(new char[] { "," });
				Console.WriteLine(string.Format("{0}={1}", m_Splitted[0], m_Splitted[1]));
			}
		}
	}
 
Result:
1="One"
2="Two"
3="Three"
  Permalink  
v5
Comments
Hawkeye101 at 24-Jul-13 0:59am
   
It didnt work! This is my csv format!
 
USD,125.49,132
CAD,124.47,135.98
BHD,325.84,686.98
DKK,21.72,23.84
SEK,15.7,16.75
CHF,134.24,147.11
JPY,1.5493,1.6625
KWD,417.01,934.14
ZAR,11.14,28.18
NOK,21.24,23.35
HKD,15.97,17.06
OMR,316.59,670.88
QAR,33.76,71.14
SAR,27.78,58.62
AED,33.02,70.52
NZD,100.63,109.81
SGD,85.37,89.5
INR,0,3.0896
MYR,39.33,85.3
GBP,203.03,215.54
AUD,129.59,138.96
THB,3.3,7.16
BND,99.22,209.26
EUR,164.59,175.44
JOD,158.81,344.08
CNY,17.38,21.43
Winston Madiano at 24-Jul-13 1:20am
   
What is the exception(error)?
Winston Madiano at 24-Jul-13 1:46am
   
I had the above code tested and its running fine. try to set Option Strict = Off.
Good luck

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 530
1 mhegazy94 460
2 Ravi Bhavnani 230
3 Kornfeld Eliyahu Peter 185
4 Shemeemsha RA 160
0 Sergey Alexandrovich Kryukov 7,205
1 OriginalGriff 6,801
2 CPallini 5,350
3 George Jonsson 3,644
4 Gihan Liyanage 2,797


Advertise | Privacy | Mobile
Web03 | 2.8.140922.1 | Last Updated 25 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100