Click here to Skip to main content
15,886,833 members
Please Sign up or sign in to vote.
2.78/5 (4 votes)
See more:
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!


C#
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
Comments
MuhammadUSman1 24-Jul-13 0:39am    
I add solution check it, you can read all data easily and perform required action accordingly.
[no name] 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.
irwin.potter 5-Jul-17 5:39am    
Here is another solution for reading .csv in c#. Actually you can use exactly the same approach for reading any other Excel format.

0) Split won't work in many cases

1) Rive[^] instead
 
Share this answer
 
Comments
lukeer 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.
Try this 

C#
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
      {

      }
}
 
Share this answer
 
Comments
kesav prakash 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 25-Jul-13 3:11am    
Yes, you're right. I totally missed the myString.Split() section.
kesav prakash 25-Jul-13 7:22am    
great you are welcome.
Just include System.IO on top and Enjoy.
That is
C#
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:
C#
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();

           }
      }
   }
 
Share this answer
 
v4
Comments
Hawkeye101 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
Surendra Adhikari SA 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.
 
Share this answer
 
Hi Hawkeye101399 try following code. with out any external library.

C#
//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

                    
                }
 
Share this answer
 
Try Splitting them.
Lets say we have Csv file that contains the folowing:
1,"One"
2,"Two"
3,"Three"

VB
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#

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"
 
Share this answer
 
v5
Comments
Hawkeye101 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 24-Jul-13 1:20am    
What is the exception(error)?
Winston Madiano 24-Jul-13 1:46am    
I had the above code tested and its running fine. try to set Option Strict = Off.
Good luck
Member 10741788 3-Nov-16 7:16am    
this is my csv file format
Date, USD, JPY, BGN, CZK, DKK, GBP, HUF, PLN, RON, SEK, CHF, NOK, HRK, RUB, TRY, AUD, BRL, CAD, CNY, HKD, IDR, INR, KRW, MXN, MYR, NZD, PHP, SGD, THB, ZAR, ILS,


24 October 2016, 1.0891, 113.29, 1.9558, 27.021, 7.4394, 0.89015, 308.53, 4.3166, 4.5065, 9.7050, 1.0821, 8.9855, 7.5083, 67.7970, 3.3501, 1.4282, 3.4200, 1.4547, 7.3775, 8.4478, 14178.99, 72.7975, 1234.29, 20.2263, 4.5444, 1.5215, 52.562, 1.5159, 38.119, 15.1167, 4.2057,

I want convert this
Date Currency Rate
06/10/2016 AED 0.3514
06/10/2016 ARS 0.0843
03/11/2016 BGN 0.7403
06/10/2016 BHD 3.4306

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900