Reading CSV file and storing values into an array

后端 未结 19 1436
猫巷女王i
猫巷女王i 2020-11-22 06:35

I am trying to read a *.csv-file.

The *.csv-file consist of two columns separated by semicolon (\";\").

I am able

相关标签:
19条回答
  • 2020-11-22 07:10

    LINQ way:

    var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
    var csv = from line in lines
              select (from piece in line
                      select piece);
    

    ^^Wrong - Edit by Nick

    It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

    var csv = from line in lines
              select (line.Split(',')).ToArray();
    
    0 讨论(0)
  • 2020-11-22 07:14

    My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:

    using Microsoft.VisualBasic.FileIO;
    
    var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
    using (TextFieldParser csvParser = new TextFieldParser(path))
    {
     csvParser.CommentTokens = new string[] { "#" };
     csvParser.SetDelimiters(new string[] { "," });
     csvParser.HasFieldsEnclosedInQuotes = true;
    
     // Skip the row with the column names
     csvParser.ReadLine();
    
     while (!csvParser.EndOfData)
     {
      // Read current line fields, pointer moves to the next line.
      string[] fields = csvParser.ReadFields();
      string Name = fields[0];
      string Address = fields[1];
     }
    }
    

    Remember to add reference to Microsoft.VisualBasic

    More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html

    0 讨论(0)
  • 2020-11-22 07:14

    look at this

    using CsvFramework;

    using System.Collections.Generic;

    namespace CvsParser {

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Order> Orders { get; set; }        
    }
    
    public class Order
    {
        public int Id { get; set; }
    
        public int CustomerId { get; set; }
        public int Quantity { get; set; }
    
        public int Amount { get; set; }
    
        public List<OrderItem> OrderItems { get; set; }
    
    }
    
    public class Address
    {
        public int Id { get; set; }
        public int CustomerId { get; set; }
    
        public string Name { get; set; }
    }
    
    public class OrderItem
    {
        public int Id { get; set; }
        public int OrderId { get; set; }
    
        public string ProductName { get; set; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
    
            var customerLines = System.IO.File.ReadAllLines(@"Customers.csv");
            var orderLines = System.IO.File.ReadAllLines(@"Orders.csv");
            var orderItemLines = System.IO.File.ReadAllLines(@"OrderItemLines.csv");
    
            CsvFactory.Register<Customer>(builder =>
            {
                builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
                builder.Add(a => a.Name).Type(typeof(string)).Index(1);
                builder.AddNavigation(n => n.Orders).RelationKey<Order, int>(k => k.CustomerId);
    
            }, false, ',', customerLines);
    
            CsvFactory.Register<Order>(builder =>
            {
                builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
                builder.Add(a => a.CustomerId).Type(typeof(int)).Index(1);
                builder.Add(a => a.Quantity).Type(typeof(int)).Index(2);
                builder.Add(a => a.Amount).Type(typeof(int)).Index(3);
                builder.AddNavigation(n => n.OrderItems).RelationKey<OrderItem, int>(k => k.OrderId);
    
            }, true, ',', orderLines);
    
    
            CsvFactory.Register<OrderItem>(builder =>
            {
                builder.Add(a => a.Id).Type(typeof(int)).Index(0).IsKey(true);
                builder.Add(a => a.OrderId).Type(typeof(int)).Index(1);
                builder.Add(a => a.ProductName).Type(typeof(string)).Index(2);
    
    
            }, false, ',', orderItemLines);
    
    
    
            var customers = CsvFactory.Parse<Customer>();
    
    
        }
    }
    

    }

    0 讨论(0)
  • 2020-11-22 07:16

    Here is my variation of the top voted answer:

    var contents = File.ReadAllText(filename).Split('\n');
    var csv = from line in contents
              select line.Split(',').ToArray();
    

    The csv variable can then be used as in the following example:

    int headerRows = 5;
    foreach (var row in csv.Skip(headerRows)
        .TakeWhile(r => r.Length > 1 && r.Last().Trim().Length > 0))
    {
        String zerothColumnValue = row[0]; // leftmost column
        var firstColumnValue = row[1];
    }
    
    0 讨论(0)
  • 2020-11-22 07:17

    I usually use this parser from codeproject, since there's a bunch of character escapes and similar that it handles for me.

    0 讨论(0)
  • 2020-11-22 07:19

    Hi all, I created a static class for doing this. + column check + quota sign removal

    public static class CSV
    {
        public static List<string[]> Import(string file, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
        {
            return ReadCSVFile(file, csvDelimiter, ignoreHeadline, removeQuoteSign);
        }
    
        private static List<string[]> ReadCSVFile(string filename, char csvDelimiter, bool ignoreHeadline, bool removeQuoteSign)
        {
            string[] result = new string[0];
            List<string[]> lst = new List<string[]>();
    
            string line;
            int currentLineNumner = 0;
            int columnCount = 0;
    
            // Read the file and display it line by line.  
            using (System.IO.StreamReader file = new System.IO.StreamReader(filename))
            {
                while ((line = file.ReadLine()) != null)
                {
                    currentLineNumner++;
                    string[] strAr = line.Split(csvDelimiter);
                    // save column count of dirst line
                    if (currentLineNumner == 1)
                    {
                        columnCount = strAr.Count();
                    }
                    else
                    {
                        //Check column count of every other lines
                        if (strAr.Count() != columnCount)
                        {
                            throw new Exception(string.Format("CSV Import Exception: Wrong column count in line {0}", currentLineNumner));
                        }
                    }
    
                    if (removeQuoteSign) strAr = RemoveQouteSign(strAr);
    
                    if (ignoreHeadline)
                    {
                        if(currentLineNumner !=1) lst.Add(strAr);
                    }
                    else
                    {
                        lst.Add(strAr);
                    }
                }
    
            }
    
            return lst;
        }
        private static string[] RemoveQouteSign(string[] ar)
        {
            for (int i = 0;i< ar.Count() ; i++)
            {
                if (ar[i].StartsWith("\"") || ar[i].StartsWith("'")) ar[i] = ar[i].Substring(1);
                if (ar[i].EndsWith("\"") || ar[i].EndsWith("'")) ar[i] = ar[i].Substring(0,ar[i].Length-1);
    
            }
            return ar;
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题