将 CSV 文件转换为 DataTable 时出错将 .txt 添加到 csv 文件名

Error While converting CSV file to DataTable Adding .txt to the csv file name

下面是我将 csv 文件转换为 DataTabel 的代码。

 public static DataTable ImportCSVtoDatatable(string filepath, string strQuery )
    {
        //strQuery = "Select * From [GJ20150417044150]";
        //string filepath= @"h$\Data\GJ20150417044150.csv";

        DataSet ds = new DataSet();
        var constring = string.Format(@"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""", Path.GetDirectoryName(filepath));

        OleDbConnection con = new OleDbConnection(constring);

        OleDbDataAdapter da = new OleDbDataAdapter(strQuery, con);

        //Error Occuring on this step
        da.Fill(ds);
        DataTable dt = ds.Tables[0];
        return dt;
    }

我的程序崩溃了,我得到的错误如下:

The Microsoft Jet database engine could not find the object 'GJ20150417044150.txt'. Make sure the object exists and that you spell its name and the path name correctly.

我猜是,它正在尝试搜索 "GJ20150417044150.txt" 文件但无法获取它,因为它实际上是 "GJ20150417044150.csv" 文件并且给定路径中没有 "GJ20150417044150.txt"。

请帮助我:

1:如何消除此错误并select 将所需的 .csv 文件转换为数据表。

2:为什么这个.txt被添加到进程中的GJ20150417044150

所以这个问题的解决方案是,更改这些行:

//strQuery = "Select * From [GJ20150417044150]";
//string filepath= @"h$\Data\GJ20150417044150.csv";

至此

var fileName = Path.GetFileName(filepath); 
strQuery = @"SELECT * FROM " + fileName;

问题是正在使用的 strQuery 的值不包含完整的文件名,而只包含 GJ20150417044150 部分,Jet 引擎试图向其附加默认文本扩展名.txt,找不到名称为 GJ20150417044150 的文件。