我使用下面的代码将CSV文件加载到ADO.NET DataTable中。当CSV文件名包含某些特殊字符时,命令。填充失败。我精明到足以在命令文本中围绕文件名放置方括号:
"SELECT * FROM [{0}]"
我认为方括号是针对导致所述错误的特殊字符的保护。导致其失败的CSV文件名示例是AdventureWorks.Person.Person.csv。
public static DataTable GetDataTableFromCSV(string folderPath, string csvFileName)
{
DataTable table = new DataTable();
string connectionText = String.Format(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties='text;HDR=Yes';",
folderPath);
string commandText = String.Format("SELECT * FROM [{0}]", csvFileName);
using (OleDbConnection connection = new OleDbConnection(connectionText))
{
connection.Open();
using (OleDbDataAdapter command = new OleDbDataAdapter(commandText, connection))
{
command.Fill(table);
command.Dispose();
}
connection.Close();
}
return table;
}