Parsing CSV using OleDb using C#

吃可爱长大的小学妹 提交于 2019-11-26 16:32:50
Darin Dimitrov

You should indicate only the directory name in your connection string. The file name will be used to query:

var filename = @"c:\work\test.csv";
var connString = string.Format(
    @"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""", 
    Path.GetDirectoryName(filename)
);
using (var conn = new OleDbConnection(connString))
{
    conn.Open();
    var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
    using (var adapter = new OleDbDataAdapter(query, conn))
    {
        var ds = new DataSet("CSV File");
        adapter.Fill(ds);
    }
}

And instead of OleDB you could use a decent CSV parser (or another one).

Alternate solution is to use TextFieldParser class (part of .Net framework itself.) https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser

This way you do not have to rely on other developer who has gone for holidays. I have used it so many times and have not hit any snag.

I have posted this from work (hence I cannot post an example snippet. I will do so when I go home this evening).

It seems your first row contains the column names, so you need to include the HDR=YES property, like this:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\TEST.csv;Extended Properties="Excel 12.0;HDR=YES";

Try the connection string:

"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\TEST.csv;Extended Properties=\"Excel 8.0;IMEX=1\""
 var  s=@"D:\TEST.csv";
 string dir = Path.GetDirectoryName(s);
 string sConnection = "Provider=Microsoft.Jet.OLEDB.4.0;"
                       + "Data Source=\"" + dir + "\\\";"
                       + "Extended Properties=\"text;HDR=YES;FMT=Delimited\"";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!