locked
Read specific columns and there values from .CSV file and store it in a hashtable using C#.net RRS feed

  • Question

  • User1810310269 posted
                Hashtable ht = new Hashtable(); 
                using (TextFieldParser parser = new TextFieldParser(csv_file_path))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
                    while (!parser.EndOfData)
                    {
                        try
                        {
                            string[] fields = parser.ReadFields();
                            ht.Add(fields[0],fields[1]); //Here i need help how to insert specific columns value into a hashtable.
                        }
                        catch (Exception ex)
                        {
                            // ...
                        }
                    }
                }
    
                foreach (string key in ht.Keys)
                {
                    Console.WriteLine(String.Format("{0} : {1}", key, ht[key]));
                }


    Hi,

      I want to read specific columns from my .csv file and store the values into a hashtable. The csv file contains total of 9 columns of which i want to read 4 columns and there values(Columns names are like PeopleId,HashValue,SecurityToken and Date).

    Can you please suggest me the code to read the file data, as i am new to this.

    Thanks,

    Anand.

    Friday, August 1, 2014 12:07 AM

Answers

  • User-271186128 posted

    Hi anand,

    According to your description, I think you want to read the specific columns from .csv file. I think you could use the StreamReader reading the .csv file, and use the String.Split() Method to divide the result and get the specific columns. The following is a sample, you could refer to it.

            protected void GetCSVValue()
            {
                StreamReader sr = new StreamReader(@"D:\CSVData.csv");
                StringBuilder sb = new StringBuilder();
                DataTable dt = CreateTable();
                DataRow dr;
                string s;
                while (!sr.EndOfStream)
                {
                    s = sr.ReadLine();
    
                    string[] str = s.Split(',');
    
                    dr = dt.NewRow();
                    //because the first line is header
                    string str1 = str[0].ToString();
                    if (!str1.Equals("Id"))
                    {
                        dr["Id"] = str[0].ToString();
                        dr["Name"] = str[1].ToString();
                        dt.Rows.Add(dr);
                    }
                }
    // I test it using a GridView GridView1.DataSource = dt; GridView1.DataBind(); } protected DataTable CreateTable() { // Create a new DataTable. DataTable table = new DataTable("TestTable"); // Declare variables for DataColumn and DataRow objects. DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to DataTable. column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.ColumnName = "Id"; column.ReadOnly = true; column.Unique = true; // Add the Column to the DataColumnCollection. table.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "Name"; column.AutoIncrement = false; column.Caption = "Name"; column.ReadOnly = false; column.Unique = false; // Add the column to the table. table.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[1]; PrimaryKeyColumns[0] = table.Columns["Id"]; table.PrimaryKey = PrimaryKeyColumns; return table; }

    Hope it can help you.

    Best Regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 5, 2014 5:59 AM

All replies

  • User1558924997 posted

    I would suggest to use filehelpers multirecordengine 

    You can define your record selector to read the required field.

    Friday, August 1, 2014 1:37 AM
  • User1428246847 posted

    A hashtable contains key / value pairs. So unless you combine columns, you can't. Also note that the key must be unique.

            int key = 0;
            while (!parser.EndOfData)
            {
                try
                {
                    string[] fields = parser.ReadFields();
                    ht.add(key++,String.Format("{0}|{1}|{2}|{3}", fields[0],fields[2],fields[3], fields[8]));
                }
                catch (Exception ex)
                {
                    // ...
                }
            }

    An alternative is to make the value a new hashtable

            int key = 0;
            while (!parser.EndOfData)
            {
                HashTable ht2 = new HashTable();
                try
                {
                    string[] fields = parser.ReadFields();
                    ht2.Add("col1", fields[1]);
                    ht2.Add("col5", fields[5]);
                    ht2.Add("col6", fields[6]);
                    ht2.Add("col9", fields[9]);
                    ht.add(key++, ht2);
                }
                catch (Exception ex)
                {
                    // ...
                }
            }

    I'm not sure why you want to use a hashtable for this, a datatable might be a better option.

    PS: none of the code is tested!

    Saturday, August 2, 2014 8:39 AM
  • User-271186128 posted

    Hi anand,

    According to your description, I think you want to read the specific columns from .csv file. I think you could use the StreamReader reading the .csv file, and use the String.Split() Method to divide the result and get the specific columns. The following is a sample, you could refer to it.

            protected void GetCSVValue()
            {
                StreamReader sr = new StreamReader(@"D:\CSVData.csv");
                StringBuilder sb = new StringBuilder();
                DataTable dt = CreateTable();
                DataRow dr;
                string s;
                while (!sr.EndOfStream)
                {
                    s = sr.ReadLine();
    
                    string[] str = s.Split(',');
    
                    dr = dt.NewRow();
                    //because the first line is header
                    string str1 = str[0].ToString();
                    if (!str1.Equals("Id"))
                    {
                        dr["Id"] = str[0].ToString();
                        dr["Name"] = str[1].ToString();
                        dt.Rows.Add(dr);
                    }
                }
    // I test it using a GridView GridView1.DataSource = dt; GridView1.DataBind(); } protected DataTable CreateTable() { // Create a new DataTable. DataTable table = new DataTable("TestTable"); // Declare variables for DataColumn and DataRow objects. DataColumn column; DataRow row; // Create new DataColumn, set DataType, // ColumnName and add to DataTable. column = new DataColumn(); column.DataType = System.Type.GetType("System.Int32"); column.ColumnName = "Id"; column.ReadOnly = true; column.Unique = true; // Add the Column to the DataColumnCollection. table.Columns.Add(column); // Create second column. column = new DataColumn(); column.DataType = System.Type.GetType("System.String"); column.ColumnName = "Name"; column.AutoIncrement = false; column.Caption = "Name"; column.ReadOnly = false; column.Unique = false; // Add the column to the table. table.Columns.Add(column); // Make the ID column the primary key column. DataColumn[] PrimaryKeyColumns = new DataColumn[1]; PrimaryKeyColumns[0] = table.Columns["Id"]; table.PrimaryKey = PrimaryKeyColumns; return table; }

    Hope it can help you.

    Best Regards,
    Dillion

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 5, 2014 5:59 AM
  • User1428246847 posted

    and use the String.Split() Method to divide the result and get the specific columns

    You can not reliably read a CSV file by simply splitting on the separator (e.g. ','). The fields themselves can contain the separator in which case the split will return an incorrect result.

    Tuesday, August 5, 2014 7:43 AM