此方法不会抛出异常,也不会从它读入DataTable的csv文件中返回行。我不知道我做错了什么。
非常感谢任何帮助。
public string ImportCsvFile(string filePath)
{
FileInfo file = new FileInfo(filePath);
//string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" + file.DirectoryName + "\" Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";
string connString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};" + @" Extended Properties={1}", file.DirectoryName, "'Text;HDR=YES;FMT=CSVDelimited'");
using (OleDbConnection con = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", file.Name), con);
// Using a DataTable to process the data
try
{
con.Open();
ds = new DataTable("MyTable");
OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
adp.Fill(ds);
foreach (DataRow row in ds.Rows)
{
System.Diagnostics.Debug.WriteLine(row.ToString());
}
}
catch (Exception error)
{
String errorString;
errorString = "Error occurred while importing data from source file." + System.Environment.NewLine +
"Error Message: " + error.Message + System.Environment.NewLine +
"Stack Trace: " + error.StackTrace;
return errorString;
}
}
return "File imported to DataTable";
}
答案 0 :(得分:1)
事实证明,这段代码很好。这是问题的csv文件。有某种类型的文件损坏或文件格式不兼容。