我似乎无法使用以下连接字符串读取 .csv 文件:
var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Uploads\\countrylist.csv");
string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=Delimited""", fileName);
OleDbConnection oledbConn = new OleDbConnection(connectionString);
oledbConn.Open();
它给出了以下错误:
'D:\arrgh\arrgh\Uploads\countrylist.csv' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
我确认文件在那里。这里发生了什么?
最佳答案
好吧,我进一步挖掘了一下,似乎我的连接字符串是错误的。对于 CSV 文件,您无需指定实际文件名,而是指定它所属的目录,例如。
var fileName = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, "Uploads\\");
string connectionString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=""text;HDR=YES;FMT=Delimited""", fileName);
OleDbConnection oledbConn = new OleDbConnection(connectionString);
oledbConn.Open();
var cmd = new OleDbCommand("SELECT * FROM [countrylist.csv]", oledbConn);
然后您在 SelectCommand 中指定文件名。多么奇怪的做事方式。它现在对我有用。
关于c# 读取 csv 文件给出的路径无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1458068/