Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

c# read csv file save to database dynamically

  private readonly DataTable dt = new DataTable();

        /// <summary>
        /// Read CSV file and save to DataTable dynamically
        /// </summary>
        /// <param name="xmlFilePath"></param>
        /// <param name="csvFilePath"></param>
        /// <returns></returns>
        public DataTable Read(string xmlFilePath, string csvFilePath)
        {
            try
            {
                var headrs = File.ReadLines(csvFilePath).First().Split(',');
                foreach (var item in headrs)
                {
                    dt.Columns.Add(item.ToString(), typeof(string));
                }

                string[] lines = File.ReadAllLines(csvFilePath);
                foreach (string line in lines.Skip(1))
                {
                    string[] columns = line.Split(',');
                    dt.Rows.Add(columns);

                }

                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }	
 
PREVIOUS NEXT
Tagged: #read #csv #file #save #database #dynamically
ADD COMMENT
Topic
Name
6+1 =