Reading CSV files using C#

后端 未结 12 2493
野的像风
野的像风 2020-11-21 22:49

I\'m writing a simple import application and need to read a CSV file, show result in a DataGrid and show corrupted lines of the CSV file in another grid. For ex

12条回答
  •  礼貌的吻别
    2020-11-21 23:35

    First of all need to understand what is CSV and how to write it.

    1. Every next string ( /r/n ) is next "table" row.
    2. "Table" cells is separated by some delimiter symbol. Most often used symbols is \t or ,
    3. Every cell possibly can contain this delimiter symbol (cell must to start with quotes symbol and ends with this symbol in this case)
    4. Every cell possibly can contains /r/n sybols (cell must to start with quotes symbol and ends with this symbol in this case)

    The easiest way for C#/Visual Basic to work with CSV files is to use standard Microsoft.VisualBasic library. You just need to add needed reference, and the following string to your class:

    using Microsoft.VisualBasic.FileIO;
    

    Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.

    Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array. You can find my class by the following link: https://github.com/ukushu/DataExporter

    Simple example of using:

    Csv csv = new Csv("\t");//delimiter symbol
    
    csv.FileOpen("c:\\file1.csv");
    
    var row1Cell6Value = csv.Rows[0][5];
    
    csv.AddRow("asdf","asdffffff","5")
    
    csv.FileSave("c:\\file2.csv");
    

提交回复
热议问题